PHP: The Basics
Variables: Strings and Numbers

A variable is a unit of information that contains a value that can potentially change during the course of a program's execution. Variables in PHP come in all sorts and sizes. A variable can represent something as simple as a number or as complex as an object or a collection of other variables. We'll learn more about arrays later in this unit, but for now let's take a look at the simpler variables to deal with: numbers and strings. We'll see how to set their value, add them together (or, for strings, concatenate them into a single string), and output them like we did with our Hello World example in the Intro tutorial.

Note that strings of text are actually arrays, and we'll see evidence of this when we talk about arrays. However, they are often treated in the syntax as simpler variables because of how easily their values are set and manipulated, and therefore are worth covering sooner than later.

First of all, note how variables are written. They are preceded with a dollar sign (\$). This is not typical in languages like C and Java, so it may seem new to you even if you have prior programming experience. Second, note that there is no declaration of the type required in PHP. PHP dynamically types variables depending on the value that they contain. Whereas in Java or C you might have to type "var x = 1", in PHP you can simply type "\$x = 1". \$x will automatically be considered a number unless you do something to suggest that it should be a string, such as wrap the 1 in quotes or insert it into another string. Finally, note how I add the values together in two different ways when creating the \$ab and \$cd values: once using "+" and once using ".". The addition symbol is used to add numeric values, whereas the dot is used to concatenate strings. In fact, take a look at what happens when you use a "." to join the values of \$a and \$b near the end of the script: It considers "1" and "2" to be characters and strings them together into the string "12" instead of adding them up to the number 3.

Logical Conditionals
If...else...

The code block that follows demonstrates how to use if...then logic to write conditional code. In our example, we use two blocks: a simple if-clause that only runs if the condition we check for is true (if \$x is 1, which it is), and then a more complex if...else combo. In the latter example, the condition is not true (\$y is not 'test' or 'TEST', so it fails both checks), and therefore the code within the final 'else' part of the block set is run as a default.

Also: take a look at the way I included double quotes inside of the string I created in the 'else' clause. The backslash preceding the quotes that are actually output is called an 'escape' slash. It indicates that the character coming next is just a regular character and not meant to perform the special function it might otherwise perform in syntax. In this case, I'm saying that these two double-quote characters should just be output as double-quotes, as opposed to considering them to be the beginning or end of a string in the code syntax. (Note that I don't have to escape the single quotes because I'm using double quotes around my big string, so the single quotes aren't considered anything special to begin with. But sometimes you might need to do the same thing with single quotes, or even other characters.)

If...else...
More Logic: Using a Switch

In our example above, we used a series of if/else/else statements to determine what to do based on the value of something. However, if you're checking a single value, and not a more complex set of conditionals, and there are more than two distinct possible options, a 'switch' block can be useful. It's very similar to if...else, but also allows for some interesting variation in logic, which we'll see in some examples below. Let's first look at a switch that mimics the functionality of what we saw above, but this time just sticking to numbers:

A 'switch' call takes one expression within its parentheses, and then runs through the various switch options, executing each one if the value presented matches the one in the expression in the parentheses. If a 'break' is called within a case block, then the switch block ends and none of the other cases are considered. Let's see what happens if we neglect to include these 'break' statements:

Because we didn't break after finding the right case, our switch continued through the cases, eventually hitting the default case, which is ALWAYS executed if the switch gets that far. Sometimes this is useful, but in many cases, this is used much like the 'else' clause, and is only intended to execute if no other match is found.

Looping

Loops are common within code. It is often the case that a program needs to continue to do something until a certain condition is met, or perhaps run through a collection of data such as an array of query results, doing something for each item it finds.

While-Loops

'While' loops are useful for doing something until a condition is met:

The loop above will run as long as \$x is less than 5. Since \$x starts at 0, the loop runs once, prints 0, and sets \$x to 1 (by incrementing using the '++' shorthand). This process repeats as long as \$x is less than 5, and therefore counts to 4: Once \$x is incremented to 5, the while-loop will no longer run, and the program will continue, so we'll never see it print the number 5.

For-Loops

If you know (or at least your code knows) that you have a distinct set of values to loop through (like an array of results), a for-loop is a variation of while-logic that allows you to loop through a set in a slightly less robust way. Unlike a while-loop, there are three expressions/statements inside the parentheses of a for-loop. The middle one is the condition to be met (similar to what's in the while-loop parentheses). The first statement sets an initial condition (similar to what we did outside of our while-loop before beginning, by setting \$x to 0). Finally, the third/last statement tells the loop what to do after it finishes each iteration. We can write something very similar to our while-loop above using for-loop syntax instead:

So when should you use while-loops vs. for-loops? Typically you'll use for-loops if you're looping through a set of values (again, like an array), whereas you'll probably use a while-loop if you're just waiting for something to happen in your code and you don't necessarily have a set of items to run through already. For example, you might use a while-loop to do something until a particular time of day arrives, or until a certain process has completed on the server. On the other hand, you might use a for-loop if you've retrieved an array of row results from a query and need to run through each one and output something.

Arrays

In previous examples, we saw that we are able to loop through sets of values by using for-loops. Very often, what we are looping through is an array, which is a collection of values contained within a single variable. For example, if you perform a SELECT query and it returns a set of database rows, these rows will likely be returned to your code as an array of rows. Each row, in turn, will be an array of information about each listing. So, for example, you might get 10 user rows back, and each row may contain a 'firstname', 'lastname' and 'birthdate' value. Arrays can therefore be described as having a number of "dimensions".

One-Dimensional Arrays

A simple one-dimensional array is a simple set of items. For example:

Take a look at how we output the arrays in the example above. the 'print_r' (print recursive) function automatically prints out the structure of complex variables like objects and arrays, including their key names and the values stored. This is a useful function for viewing the structure of variables when debugging your code.

In the example above, we see two ways that exactly the same array can be constructed: by including the comma-separated values inside the parentheses as seen in the first example, or by adding each value to the array individually using the empty-square-bracket notation in the second example. In both cases, a single-dimensional array is created, and it automatically uses numeric keys, starting with 0. (It is common to start counting with 0 in programming. This works out nicely for certain mathematical calculations later when examining the length of arrays or strings and then referencing certain positions in them based on that length.)

Multi-Dimensional Arrays

Multi-Dimensional Arrays are simply arrays of arrays. A 2D array is a array containing a set of 1D arrays that then each contain simple values. Similarly, a 3D array is an array of 2D arrays, and a 4D array is an array of 3D arrays.

Compare array dimensionality to geometric dimensionality. A simple point has no dimension. A line is a stack of points in one dimension. A square is a stack of lines in another direction. A cube is a stack of squares in another dimension. A hypercube would be... you get the idea. So a 1D array is a stack of values, a 2D array is a stack of 1D arrays, etc.

Of course, while print_r is useful for debugging, it's more likely that we're going to actually want to dig through our data and put it to use in some output of calculation of some sort. This is when for-looping comes into play. Instead of just outputting the raw array using print_r, let's loop through and output some HTML for a table:

Hey, what's this 'foreach' nonsense? It turns out that there are at least two ways to loop through data using for-syntax. If you don't want to explicitly track what numbered item you're currently on, or you don't necessarily using numbered keys (for example, our 2nd-dimension is keyed using 'firstname' and 'lastname', not '0' and '1'), then 'foreach) lets you simply say "do this for each one you find, no matter what the key is". We can still use the normal "counting" syntax in our outer loop because that array uses the default numeric indexing (0,1,2,etc).

Our table was nice, but it didn't have column headers. The 'foreach' variation of our for-loop allows for an interesting feature: you can create a variable reference to not only the value in each iteration through the loop, but to the key as well. Take a look at the bolded code below to see how we keep track of whether we're in the first iteration of the loop and, if so, write out a header row before writing out the normal row of data:

Functions
An example with Numbers

There are many mathematical functions for dealing with numbers. Let's just look at two simple ones, namely max() and min(), which take any number of arguments (1 or more numbers) and return the highest or lowest one, respectively:

What's interesting to note is this concept of 'return' values. The 'return' value of a function, if provided, is the value that the function will pass to a variable that is set using it, or into another function that uses it. For example, look at the first three lines of the code above. \$a, \$b and \$c are all being set to the result of applying the max() and min() functions. The 'return' value of these functions is what each variable gets set to. Similarly, if the function is embedded as the argument of another function (specifically see line 3), then the return value will be used in the next function call as it works its way from inside out.

Working with Strings

There are many functions that apply to strings. They can be used to split strings into an array, grab a substring from within a string, replace one or more values within a string and much, much more. Let's look at some code that demonstrates just a small sampling of these functions:

Working with Arrays

There are also many functions that manipulate arrays. I can't begin to address all (or even many) of these functions, but I'll point out a few that are particularly common, and make a few notes about noteworthy pieces of the code:

User-Defined Functions

In addition to the many, many pre-existing functions and classes available in the PHP library, programmers can also define their own functions to carry out complex series' of steps. Let's take a look at one of our examples from the unit on arrays, but this time implement a custom function to carry out the task of displaying a table from an array of data:

As you can see, a function can be declared by simply typing 'function theNameOfTheFunctionYouAreCreating()', and then including (in order) a list of the parameters (passed-in variables) that you expect to be provided whenever the function is called. In our case, we only require one value: \$data. The \$data passed in is expected to be an array of arrays with some specific keys, such as 'First Name' and 'Last Name'. If \$data that conforms to these expectations is passed in, then our function will be able to do what we expect.

Recommended next: Using a Database: MySQL
{"ft_lang_label":"__label__en","ft_lang_prob":0.9268408,"math_prob":0.8821313,"size":12583,"snap":"2020-45-2020-50","text_gpt3_token_len":2751,"char_repetition_ratio":0.122028776,"word_repetition_ratio":0.00625,"special_character_ratio":0.21989986,"punctuation_ratio":0.099486776,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9715432,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-10-19T15:04:01Z\",\"WARC-Record-ID\":\"<urn:uuid:88d0669e-624e-4305-aa4b-5261fd847f20>\",\"Content-Length\":\"17246\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:99902aae-2124-456e-803e-18d614deef76>\",\"WARC-Concurrent-To\":\"<urn:uuid:e73b9f41-3f6e-4f55-a95b-bd912dd12c8e>\",\"WARC-IP-Address\":\"64.111.123.125\",\"WARC-Target-URI\":\"https://trianglewebtech.com/www/tutorials/PHP/Basics/\",\"WARC-Payload-Digest\":\"sha1:JH2BPLIXOYHW7CLGY2DN6ONU6Z73VEXD\",\"WARC-Block-Digest\":\"sha1:MCWD3WENG725EXRHPHH2QR6MKFP7LJKX\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-45/CC-MAIN-2020-45_segments_1603107863364.0_warc_CC-MAIN-20201019145901-20201019175901-00519.warc.gz\"}"}