In a previous video, we looked at using logical branching structures to control which statements get executed in your code and which get skipped, depending on your data. In this video we look at one more way to control your code’s execution path – looping.
Personally, I’m a huge fan of looping code. One of my pet peeves is when I come across someone else’s code where they’re doing the same thing over and over for line after line after line, where they clearly could have just used a loop to get the same result.
There are actually 4 different looping structures that PHP supports. The first is called the ‘for’ loop. Here’s the basic syntax:
for($var1 = 0; $var1 < 20; $var1++) {
//code goes here
}
That’s the typical example anyway. The ‘for’ declaration is followed by a 3-part expression in parenthesis. The way this particular setup will work is by setting a variable called $var1 to be 0, incrementing it by 1 each time it goes through the loop, and when it’s no longer less than 20, the loop ends. So, this loop will run 20 times, unless some instruction inside the loop causes $var1’s value to change in some other way, or else exit the loop prematurely.
While going through the loop, the code has access to the current value of the $var1 variable.
Here’s a simple example:
for($var1 = 0; $var1 < 20; $var1++) {
echo ‘I am on loop number ‘ . $var1 . ‘<br>’;
}
{show output}
And you see it’s just 20 lines in ascending order.
Now, a word of caution about loops. If your condition can never be false, then you’re going to get an infinite loop. In practical terms, that’s not quite as bad in PHP as in most other languages. The PHP process gets an execution time limit, 30 seconds by default, and once it takes longer than that to finish, the server kills it. But still, you should never have an infinite loop on purpose.
Before we move on, I want to take a closer look at the three statements inside the for declaration. The first is just a base condition that gets run once just before the loop starts.
The second statement is like the code in your ‘if’ declarations. If it’s true, then the code will run. If it’s false, then the loop is finished and the code execution resumes on the line immediately after your code block.
The final statement is going to be run once at the end of each loop.
A fairly common use for the ‘for’ loop in most languages that have it is iterating over arrays. Assuming your array has integer indexes, you just use the loop counter variable, in this case $var1 as your key to access each value in turn. However, in PHP, the language gives you a specialized control structure just for looping over arrays, called the ‘foreach’ loop. And that’s what we’re going to look at next here.
So, starting with an array ‘$array1’, I use the special syntax below to iterate over it, and assign each of the array’s values to the variable $var1 in turn. So, as I’m going through the loop, my code will be able to act on every value in the array just by referencing $var1.
$array1 = range(0, 19);
foreach($array1 as $var1) {
echo ‘I am on loop number ‘ . $var1 . ‘<br>’;
}
{show output}
The range function is just one of those handy ones built into PHP. In this case, I give it a minimum and maximum value, and it gives me an array with each integer in that range as its values.
Foreach has another way of being invoked though, and that lets you get both the keys, and the values:
foreach($array1 as $key => $value) {
echo “Key $key has value $value<br>”;
}
{show output}
This is particularly useful with associative arrays, where both the key and the value are significant. It’s also something you can’t do just iterating over an array in a for loop.
Now, occasionally, you’ll want to actually change the values of an array as you iterate over them. It’s not possible to change the keys, but to change the values, you use a special operator – the single &:
foreach($array1 as &$value) {
$value *= 2;
}
unset($value);
foreach($array1 as $key => $value) {
echo “Key $key has value $value<br>”;
}
So, this bit of code is going to double each value in the array. The call to unset at the end there is important because after the final loop, $value is still connected to the last value in the array. Using unset just unlinks that variable from the array, and avoids the risks of weird or unexpected behavior. But we talk about variable references in a later video, so I won’t go into more detail here.
{show output}
By the end of loop, the values in $array1 will all be doubled.
The next two loop types I want to introduce you to are the while and do while loops. These are sort of like for loops in a sense, except they only have the conditional expression. There’s no initializer and no expression that gets run with each loop. With the while loop, so long as its condition evaluates to true, it will continue to run. The code within the block is responsible for changing the data such that the condition no longer evaluates to true. Here’s a simple example:
$var1 = 10;
while($var1 > 0) {
echo ‘The current value is ‘ . $var1 . ‘<br>’;
$var1–;
}
{show output}
While $var1 is greater than 0, it prints out its value and then decreases it by 1. Eventually the while condition is no longer true and the code exits the loop. In the case of the while loop, if the condition is false to begin with, the loop will never execute. The difference with the do while loop is that you are guaranteed to run your loop at least one time. Instead of evaluating the condition, and then running the code if it’s true, it runs the code, and then checks the condition to determine whether to run it again.
{change $var1 = 10 to $var1 = 0}
{show output}
See? As a while loop, it didn’t run. Now if we change it to a do while loop, all we do is place the ‘while’ statement, with its conditional expression, after the closing brace. And we put the word ‘do’ up here in front of the opening brace:
{modify loop}
{show output}
The loop code ran once, and then since the condition was false, it didn’t run again.
The last thing I’m going to show you when it comes to loops is how to use the special ‘break’ and ‘continue’ statements. We already got a look at the break statement in the context of ‘switch’, and in the case of loops it does the same thing. When your script hits a break statement for whatever reason, it exits whatever loop (or switch statement) it happens to be in:
$var1 = 10;
while($var1 > 0) {
echo ‘The current value is ‘ . $var1 . ‘<br>’;
if($var1 == 5) {
break;
}
$var1–;
}
If you’re inside of two or more loops, and need to break out of all of them, you can use the break statement followed by the number of loops and switches you want to break out of:
$x = 32;
for($i = 0; $i <10; $i++) {
for($j=10; $j > 0; $j–) {
if($j*$i == $x) {
break 2;
}
}
}
echo “($i, $j)”;
On the other hand, sometimes you don’t want to exit a loop entirely, but you do want to skip to the next iteration. Well, in that case continue is what you need. In the case of a switch statement, since there is no iteration taking place, it will perform exactly the same as a break. But in a loop, it simply halts the current iteration and skips ahead to the next one, if one exists. If there are no further iterations to perform, the loop simply ends:
for($i = 0; $i<30; $i++) {
if($i % 4 == 3) {
continue;
}
echo ‘I am on iteration #’ . $i . ‘<br>’;
}
Like break, continue can also be used with multiple loops. Suppose I have a couple of nested for loops. If the inner loop hits ‘continue 2’, then it’ll break out of that loop completely, but then begin the next iteration of the outer loop.
That concludes the lesson on control structures. They’re a little tricky the first time you see them, but they’re indispensable in good coding.
February 11 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on Control Structures, part II
Now that we’ve taken a look at how to build variables, we’re going to look at how to build the basic logic, called the control structures, that let you manage how your script is executed. Without any control structures, your code will simply execute each line until it reaches the end. But usually you want to change the script execution path based on your data. Control structures give you that flexibility.
The first control structure is called the if statement. All it does is evaluate an expression, and if that expression is true, it invokes the code in its branch. If not, its branch gets skipped.
We define it like this:
if(expr) {
//code to execute
}
The braces define your branch, and they can include as many lines as you need. The parenthetical statement between the word ‘if’ and the opening brace is your test expression.
So, here’s a pretty simple example:
$var1 = true;
if($var1) {
echo ‘I am the true branch!’;
}
{show output}
Because $var1 was true, we went into the branch and saw the somewhat pompous output from it, but if we change $var1 to false, our output is blank:
{modify $var1}
{show output}
Now, if we want, we can define another branch that only gets executed when the expression is false. And we do that with an ‘else’ branch, like so:
if($var1) {
echo ‘I am the true branch!’;
} else {
echo ‘I am the false branch!’;
}
{show output}
This time, since $var1 was still false, we ended up going through the code in the else branch, resulting in the output we see here.
Now sometimes, if and else are insufficient. They only give you the ability to test for two different outcomes. But what if you want to create more than two possible outcomes? If that’s what you want, you can create one or more ‘elseif’ branches. An elseif branch can be created with or without a space between the words ‘else’ and ‘if’ – both work. Just follow it with an expression, the same as declaring an ‘if’ branch, and then define your branch inside braces again:
$var1 = 1;
if($var1 > 0) {
echo ‘$var1 is greater than 0’;
} elseif($var1 == 0) {
echo ‘$var1 is 0’;
} else {
echo ‘$var1 is something else’;
}
{show output}
Now, if both your ‘if’ condition and your ‘elseif’ condition are true, only your ‘if’ branch will be run. PHP stops checking your test expressions after it finds one that evaluates as true. Once it does, it runs that branch and then continues executing below the close of your entire control structure.
As far as the branches go, you’ve got to have an if branch, but the else and else-if branches are entirely optional. And you can have as many elseif branches as you like, but you can only have one else branch connected to an if branch, and it always has to come at the end after any elseif branches you may have defined. Logically this makes sense since else just gets run if no if or elseif branch runs. Another else or a follow-on elseif branch just wouldn’t make any sense.
Now, let’s imagine you have a situation where you’ve got lots of if and elseif branches testing one variable for a whole range of possible values. As in, if $var1 is 1 do this, else if it’s 2 do this, else if it’s 3 do this, and so forth. For this situation, PHP provides us with another control structure called a switch statement.
{show ready-made example script with switch}
In the opening of the switch statement, I tell the script which variable I’m testing the value of. Each of the case statements then provides a value to test that variable against. If the variable’s value matches the value of the one in the case statement, it executes that statement. It continues execution until it encounters a break. If I remove the break,
{remove break from the case that is going to match}
{show output}
it will execute the next case’s instructions even though the variable doesn’t match it’s comparator. Here you can see that that’s happened. Sometimes, I actually want that behavior, for instance when I want the same action to happen for more than one case. But most of the time we want to remember that break.
There’s a couple other important things to keep in mind about the switch statement. First, you can only compare simple types – like floats, strings, and ints. Second, the comparison is loose, so the string ‘123’ matches the int one hundred twenty three. Basically it’s the double-equal sign comparison instead of the triple-equal sign. And third, you can do comparisons with variables and expressions, so long as they evaluate to a simple type.
Alright, now the next thing I want to show you is the default statement:
{show example}
This is basically your else statement with a new name. This statement’s code will get used if none of the cases above it match. You set up a default statement whenever you want to make sure that some code gets executed no matter what:
{show output}
There is one last secret with switch statements, and this is something that not many PHP developers even know about. Those case statements can actually do more than just test whether your test variable equals some value. You can actually do any of the logical tests between a variable and a simple value. This is great when you have, say, a float, and you need to build case statements that test not for a precise value, but for an entire range. To do that, you place your test in parenthesis after the word ‘case’. You can only test the variable you declared in your switch statement, and again, you can only test it against a simple type value, but now you have the freedom to test more than just straight “$a == 2” or something like that. Here’s an example:
{show example}
{show output}
That’s it for part I of control structures. In the next video we’re going to look at loops.
February 09 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on Control Structures, part I
We’ve already talked about PHP variables, now we’re going to look at PHP constants. As the name suggests, once you define a constant, its value doesn’t change, and your script can’t un-define it.
PHP comes with many constants built-in for use in situations that require you to interact with certain built-in functions. Generally, these constants are just integers that have no special significance outside their special cases where they’re needed. Here’s where you can find a complete list of these pre-defined constants. {show website} A few more seem to get added with every new release of PHP, so depending on how much time has passed from when this video was recorded to when you started watching it, there could be any number of new constants added to the language. The best way to find out is to check the manual.
Technically, a constant can hold the value of any scalar type. That means ints or strings, which is what you’ll usually see, and also floats and booleans – no arrays or objects. Also, unlike a variable, constants are always global in scope, so it’s important to make sure that you don’t define the same constant more than once. If you try to define a new constant with the same name as one that already exists, you’re going to trigger a fatal error.
Why might you want a constant? Well, let’s look at what a constant gives you. Here’s a simple example:
define(‘MY_FIRST_CONSTANT’, 33);
Notice I chose to use all upper-case letters for my constant’s name. Much like variables, all constants must begin with either a letter or the underscore character, and may only contain letters, the underscore, and numbers in their labels. The names are also case-sensitive, so technically there is no built-in reason to prevent me from using lower-case letters. However, convention states that constants should have descriptive upper-case names, in order to make it obvious that they’re constants.
Now, as far as this one goes, I just picked a random number out of my head and set it as the value. The most important part about a constant isn’t usually the value so much as the name. By having a meaningful name like this, I can incorporate it into my code’s logic. If I want to control what happens in a particular situation, I can create a constant that describes the situation I’m watching for, test whether or not a variable with that value is present, and control what happens next accordingly.
And since a constant’s name is meaningful to a human, when you see it, it ought to be clear what it’s intended to do. Here’s a practical case:
{show example code}
This particular example uses a constant, passed by some calling script, to determine what test to use in order to compare two values. Since GREATER_THAN is more meaningful than the number 3, constants in this situation make it easier to keep the code organized.
Like I said earlier, you want to make sure you don’t define the same constant more than once. To assist you in that, PHP gives you a function called ‘defined’. Call it on a string, and it will return true if that constant has been defined by that point in the script’s execution, and false if it hasn’t.
{show example code and output}
And if for some reason, you ever need to use a variable to hold the name of a constant, and you want to get that constant’s value, PHP provides a function called ‘constant’. Call it on your variable, and it’ll output the value of the constant it refers to, if any.
{show example code and output}
You’ll encounter constants from time to time as you work with PHP’s library of built-in functions, whether you choose to define your own or not. But some of the most interesting constants built into PHP technically aren’t constants at all. These are the magic constants.
All of the magic constants use a similar syntax – 2 underscore characters, followed by an upper-case name, and then two ending underscores. And they get their name from the fact that they look like constants, but their values depend on the contexts in which they’re used.
Here’s the first one:
__LINE__
I can place this magic constant into my script, and wherever it is, that line number, that’s its value. Check it out:
{show example code}
{show output}
Pretty cool, huh? Practically, the most common use of __LINE__ is in debugging. There typically isn’t much call for revealing what line number in your script you’ve reached when you’re in a production environment. But when you’re looking for a bug, it can be very helpful to see how far you’ve gone.
The next magic constant is __FILE__. This time, it takes on the value of whichever file I place it in:
{show example code}
{show output}
And see if I rename the file, like so:
{show output}
It takes on the new filename. Neat, huh? Once again, mainly a tool for debugging.
If what you need is the directory of the current file, you can use __DIR__. This is a new addition to PHP 5.3. For older PHP scripts, you’ll often see:
dirname(__FILE__)
which has the exact same value. I guess the PHP engineers just decided it was time to simplify things. Typically you use it for things like searching a directory or adding a value to the include path.
There’s also a magic constant to get the name of the function it resides in, assuming it resides in one:
__FUNCTION__
I know about this constant, but I’ve never used it for anything, and I’m not entirely sure when it could be useful. Still, there it is.
The last 3 magic constants that exist as of this video deal with topics we haven’t covered yet. But here’s the PHP manual page that talks about them.
{show website}
To find it for yourself, just go to PHP.net and search the online documentation for “magic constants”.
February 09 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | 2 Comments »
Probably the most used data type in any PHP script is the string. Fundamentally, a PHP string is just a sequence of characters. However, there is more than one way to define a string, and how you define it turns out to be very important.
The first way to define a string, and the way I’ve consistently been defining them in the videos up until this point, is inside single-quotes. And with single-quotes, whatever you type inbetween your quotes is the exact value of the expression, with one exception. You can escape apostrophes inside single-quotes by using a backslash.
$quoted = ‘I don\’t break’; //$quoted gets value “I don’t break”
Double-quoted strings, on the other hand, are far more interesting in PHP. With double-quoted strings, you can embed variables that will form the contents of the string based on their value when the string’s expression is evaluated. So for instance:
$color = ‘green’;
$useVar = “I see a $color truck”; //$useVar now says ‘I see a green truck’
echo $useVar;
Now, if $color wasn’t set before the string expression was evaluated, your message would just be ‘I see a truck’.
Sometimes, you want a double-quoted string to contain a $ without getting evaluated. PHP knows that if a $ is by itself, or if it’s followed by numbers rather than letters, to leave it as a $ when evaluating the string. However, if you want to see the literal string ‘$color’ inside your double-quoted string, you just need to escape your $ with a backslash, like this:
$useVar = “I see a \$color truck”;
Escaping is particularly important with double-quoted strings. To get a literal double-quote, just place a back-slash in front of it. Same to get a literal backslash.
Something else you can do, however, is use the backslash to get a newline, carriage return, or a horizontal tab.
In order, those are:
“\n”;
“\r”;
“\t”;
This is especially useful when you’re sending your output to a file or in an email, and you need to end your lines with the appropriate line-termination character. When outputting your contents to the web of course, your audience will be much more concerned about whether you use the <br> tag, since new-lines don’t generally show up. Although, even when outputting HTML, having new-lines in places where they make sense can make your HTML much easier for a human to read.
If your double-quoted string needs to have a variable show up right in front of characters, you can use braces to let the PHP engine differentiate between the variable and the string content. For instance:
$type = ‘dodge’;
$message = “Let’s go play {$type}ball tonight!”;
echo $message;
Without the braces, PHP would look for a variable name $typeball, and on failing to find it, would replace it in with the empty string.
With double-quoted strings, you can also insert values from arrays, like so:
$var1 = array(‘one’=>’orange’, ‘two’=>’banana’);
$message = “I am hungry for the $var1[two] milkshake”;
Notice, I don’t have to use single quotes around the key when I’m in the string. As a matter of fact, if I use the single quotes around my array key, I’ll get a parse error. However, if I use braces, I can stick the single quotes in.
$var1 = array(‘one’=>’orange’, ‘two’=>’banana’);
$message = “I am hungry for the {$var1[‘two’]} milkshake”;
Now a point I want to make about single quotes versus double quotes, and it should be pretty obvious. Since double-quotes require an extra step from the interpreter before it can evaluate them, there’s a slight performance penalty. If all you need are literal strings without variables or special characters, use single-quoted strings. They’re just a little bit faster. It’s not a big deal, but it’s good practice to pick the faster option when you can.
Moving on, there are 2 other ways to define strings. They’re called NOWDOC and HEREDOC. They look pretty similar, and they’re handy when you need to put a long block of text into a variable, but they can get you into trouble if you aren’t careful.
First, NOWDOC. NOWDOC begins with three ‘less than’ signs together, followed by an upper-case, single-quoted string. You place any text you want after that opening, and then you end it with the original identifier, without any quotes. Here’s an example:
$color = ‘green’;
$myNowdocString = <<<‘MYNOWDOC’
This short line of text is standing in for a longer line of text.<br>
I see a $color truck.
MYNOWDOC;
The most important warning here is that you must have a newline right after the opening tag, and a newline right before the closing tag. And on the line with the closing tag, there can be no other characters or spaces save for the closing semi-colon. If PHP doesn’t find the exact closing tag it’s looking for, it’ll keep going down your script until it reaches the end, and will throw an error referencing the last line of your file.
What the NOWDOC syntax basically does is act like one single line in your PHP code, but lets you split it across as many lines as you need.
As with single-quotes, your text inside your NOWDOC will be interpreted exactly as it appears, with no need to escape anything.
It should be noted, that NOWDOC was introduced in PHP 5.3. Earlier versions don’t support it.
The last way to define a string is with HEREDOC syntax. And HEREDOC is to NOWDOC what double-quoted strings are to single-quoted strings. Since HEREDOC has been around longer, you can define it by using an opening tag with no quotes. But, since PHP 5.3 and NOWDOC syntax have arrived, the PHP engineers have driven home the single-quoted/double-quoted string parallel pretty hard by enabling you to define your opening tag as a double-quoted string, like so:
$color = ‘green’;
$myHeredocString = <<<“MYHEREDOC”
This short line of text is standing in for a longer line of text.<br>
I see a $color truck.
MYHEREDOC;
Since it’s analogous to a double-quoted string, that means you can embed variables and special characters in it, with all the same rules that apply to double-quoted strings. Obviously one of the main advantages to NOWDOC and HEREDOC over quoted strings is that there’s no need to escape quotes, and blocks of text can be easier to read in many cases.
When you need to combine strings together, you use a period. In PHP terms, the period is referred to in this case as the “string concatenation operator”. If you stick it in the middle of two string, or a string and something that can be converted to a string, the entire expression takes on the value of the first string joined to the second.
$color = ‘green’;
$joinedString = ‘I don\’t need any variables’ . “, but I see a $color truck.”;
And it’s not something you see everyday, but concatenation works on HEREDOC and NOWDOC strings as well. Just remember to have the period on a different line from your string ending tag.
Lastly, I want to point out that you can combine concatenation and assignment into one step. Suppose you have a variable named $string1 and you need to append some other string to the end of it. Well, you could do:
$string = $string . ‘ Now make it longer!’;
But you could get the exact same result by doing this:
$string .= ‘ Now make it longer!’;
PHP also supports a number of special functions for working with your strings, and that’s going to be the topic of a later video. In the meantime, you should now have all the tools you need to start using strings effectively in your own scripts.
February 08 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on PHP Strings
PHP supports a wide range of operators. The complete set can be found by searching the PHP manual. If you go to the manual online, you’ll find that operators have their own section in the language reference portion:
{show the cursor using the PHP manual online – documentation -> English -> Operators}
I’m going to cover just 4 types of operators in this video, but if you want to learn more, they’re covered very well in the online manual.
The first set of operators we’re going to cover are the arithmetic operators. These include the familiar operators for addition, subtraction, multiplication, and division, plus 2 others – negation and modulus. The multiplication sign in PHP is the asterisk character ‘*’, and the division sign is the forward slash ‘/’. If you use division on two integers that don’t divide evenly, your result will be a float. However, if you use division on two ints that do divide evenly, your result is an int. This is worth pointing out, because in some languages, dividing ints just cuts off anything after the decimal in order to keep the result as an int. And in some other languages, they’ll cast the result of an integer division to a float no matter whether they divide evenly or not. The PHP engineers decided on a middle way.
As for negation, it’s just the minus sign in front of a variable to get its sign opposite. So, in the expression:
$a = 5;
$b = -$a;
$b becomes -5. And:
$c = -$b;
$c becomes 5.
Modulus is just a little more complicated. It’s used to find the remainder left over from dividing two numbers. So for instance:
$a = 25 % 3;
The way this works is you take 25 and subtract as many 3’s as you can without going negative. Whatever is left is the result of your expression. In this case, that’s 25-24, which is 1. So $a has a value of 1. Now, if the first number in your expression had been ‘-25’ your result would be -1. Although, oddly enough, the sign of the number after the modulus operator makes no difference to the sign of the result. So if it had been 25 % -3 the value of the expression would still be a 1.
As far as operator precedence goes, negation has the highest precedence. Multiplication, division, and modulus all have the same precedence. And addition and subtraction together have the lowest precedence. Don’t dwell too much on it right now though, since we tackle PHP’s ability to do math in a later chapter. I’m only introducing this now because it’s just handy to be able to do a little basic arithmetic here and there in your everyday scripts.
The next type of operator we’re going to look at is the assignment operator. The basic assignment operator is just the ‘=’ sign, as we’ve already seen in previous videos. It simply assigns the value of the expression to the right of the equal sign to a variable of some sort on the left side.
There are other assignment operators though. They all boil down to something like ‘Perform an action on the variable to the left and then assign the result of that expression back to the left-hand variable.’
So, for instance, there’s an operator for incrementing your variable by some amount. Now, you could write:
$a = $a + 5;
Since it evaluates the right-hand side first, the value of $a is incremented by 5. However, PHP provides another way to do the same thing in a sort of short-hand:
$a += 5;
PHP also has assignment operators for subtraction, multiplication, division, and modulus:
$a -= 5; //produces the exact same result as $a = $a – 5;
$a *= 3; //produces the exact same result as $a = $a * 3;
$a /= 2; //produces the exact same result as $a = $a / 2;
$a %= 8; //produces the exact same result as $a = $a % 8;
If all you need is to increment or decrement a variable’s value by one, PHP supports another, even shorter, short-hand:
$a++; //identical to $a += 1 and $a = $a + 1
$a–; //identical to $a -= 1 and $a = $a – 1
The next type of operator we’ll look at are the comparison operators. These are the ones that you use when you want to compare two expressions in some way, and arrive at a value for the combined expression of either true or false.
When you want to determine whether two expressions are alike, PHP provides both an equality comparison and an identity comparison. The difference is important. For an equality test, the operator is two equal signs next to each other, like this:
$a == $b;
If $a and $b have the same value, the expression returns true. But they may not be the same thing. For instance:
$a = 1;
$b = ‘1’;
$c = $a == $b; //$c is true, because converting 1 to a string produces ‘1’ and converting ‘1’ to an int produces 1
In this case $c will hold the value ‘true’, because that’s the result of the equality test. But if we change to the identity test, which consists of 3 equal signs together, we’ll get false, because the identity test checks both the value and the type:
$c = $a === $b; //$c is now false because while they have the same value, $a and $b are not of the same type
This test is particularly useful when, for instance, a function might return 0 or false, and you need to be sure you know which one you got back. For instance, PHP provides a useful built in function called strpos. It searches one string for the first occurrence of another. If it finds that search term at the very beginning of the searched string, it returns a 0. But if it doesn’t find the term at all, it returns the boolean false. Just testing for == false would be a recipe for trouble down the line.
Now, the counterpart to the equality and identity operators are the inequality and non-identity operators. These are an exclamation point followed by an equal sign, and an exclamation point followed by two equal signs, respectively.
$a != $b; //test for different value
$a !== $b; //test for different value or type
This has different meanings for different types. A string and an int can be equal if they have the same quoted value. But a string and an int can never be identical, because they’re of different types. If two ints are equal, they are also identical. And the same is true for strings and booleans. However, for arrays, two arrays are equal if they have the same key/value pairs. But those values can be of different types so long as they pass an equality test with each other. Two arrays are only identical if they have identical key/value pairs (meaning types are also the same), and with all key/value pairs in the same order.
The remaining comparison operators are the greater than/less than operators:
$a < $b; //test whether $a is less than $b
$a > $b; //test whether $a is greater than $b
$a <= $b; //test whether $a is either less than or equal to $b
$a >= $b; //test whether $a is greater than or equal to $b
With ints, the comparison is obvious enough. You’re just checking basic math. With strings, you’r checking them alphabetically, so a string starting with an ‘a’ would be considered less than a string starting with a ‘b’. However, the comparison is also case-sensitive. So a string beginning with lower-case ‘a’ would be considered greater than a string beginning with an upper-case ‘B’. If you need to compare strings in a case-insensitive way, PHP provides some built in functions to do that. We look at those more in another chapter. With booleans, ‘false’ is less than ‘true’. And with arrays, well, it gets difficult to explain, and it’s not something you’re likely to need to do anyway.
The last operators we’re going to take a quick look at are the logical operators. And we’re only going to look at 3 of them. These are called logical operators because they’re supposed to be used with boolean logic expressions. The first, is the ‘not’ operator. It’s just a single exclamation point places in front of that expression, and all it does is flip the expression. If the expression had been true before, with the not operator it becomes false. And if it had been false before, the not operator makes it true.
The second operator is the ‘and’ operator. It consists of 2 ampersands together. You use it to string two boolean expressions together. If they were both true, the entire combined expression becomes true. But if either or both expression had been false, the combined expression is false.
$a = true && false; //evaluates to false
$a = true && true; //evaluates to true
The way the PHP engine works is by evaluating statements from left to right. If the left expression is false, it doesn’t even bother to evaluate the right-hand expression. It just returns false and skips the code to the right. You can prove this is the case by putting some code to the right that ought to cause some sort of run-time error, and code to the left that will evaluate to false:
false && array() + 5; //$a is false – no error
true && array() + 5; //throws a fatal error for unsupported operand types
The counterpart to the and operator is the or operator. It consists of two vertical bars ‘||’. If an expression on either side of the or operator evaluates to true, then the entire expression is true:
true || false; //evaluates to true
false || false; //evaluate to false
And just like the and operator will stop evaluating an expression if the first half is false, the or operator will stop evaluating an expression if the first half is true. In that case it just returns true and the second half of the expression is simply ignored.
Those are all the operators I wanted to cover in this video, but there are plenty more provided by PHP. You won’t need them to complete any of the exercises at the end of this chapter, but if you want to learn them just in case you need them in the future, as always, I refer you back to the PHP manual.
{show website http://us2.php.net/manual/en/language.operators.php}
February 07 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on Logic and Operators
An array is a data structure for grouping values. Each value is associated with a key that can be used to reference it. Arrays are pretty common across programming languages, but PHP arrays have some quirks that can sometimes throw a new programmer off.
For one thing, since PHP is so loosely typed, you can define a variable as an array just by starting to use it as one. For another, PHP arrays can hold mixed types. That means an array can hold objects, integers, strings, booleans, even other arrays. And PHP arrays can expand as needed. There’s no need to declare in advance how big an array is or take any special action to increase its size once you start using it. And PHP supports both numerically-indexed arrays and associative arrays – that is, arrays that have strings for keys.
Let’s start by looking at the basic array creation syntax:
$a1 = array();
The function ‘array’ is actually a language construct. When it’s called this way, it generates a new, empty array, and assigns it to the variable $a1. In order to add values to it, you use square brackets. Here’s one way to do that:
$a1[] = 5;
In this case, the array gets the value 5. And since no key was specified, it automatically just gets the next number based on a 0-indexed sequence. Since in this case the 5 is the first value in the array, it gets assigned to the first index 0. If I want, I can specify the key for an element I add:
$a1[3] = 10;
And now the array has 2 elements. The key 0 refers to the value 5 and the key 3 refers to the value 10. Now, if I go back and use empty brackets again, like this:
$a1[] = ‘next’;
The PHP engine looks at the highest integer key already being used, and sets the value ‘next’ to an integer key that’s one number higher. So, $a1 now holds the value ‘next’ at the key 4.
Now, if I want to do these steps in one line, the array function lets us do that. All I have to do is:
$a1 = array(5, 3=>10, ‘next’);
The values are added to an array using a comma-separated list. Also, notice the double-arrow. That’s how you specify the key for a particular value.
We can also use string keys. When you do that, you’re making an associative array. Performance-wise, associative arrays are just a little slower than arrays that use numeric indexes, but you can gain a lot when it comes time to access your values, since associative arrays allow you to assign meaningful names to your array’s keys.
Here’s an example of using a string as an array key:
$a2 = array(‘joe’=>’orange’, ‘anne’=>’peach’, ‘phil’=>’banana’);
$a2[‘sandy’] = ‘apple’;
When it comes time to access the values in an array, we turn to the square bracket syntax again:
echo $a2[‘anne’]; //prints out ‘peach’
As far as keys, only ints or strings can be used. Other data types won’t work. If you want to have an array inside an array, that’s easy to do:
$a3 = array(‘first’ => array(4, 5, ‘hello’=>’world’), ‘second’=>array($a1, $a2));
If I want to access one of the inner array’s values, I need to use more than one set of square brackets:
echo $a3[‘first’][‘hello’]; //prints out ‘world’
You can embed arrays as many layers deep as you want.
Another important point about PHP arrays is that PHP supports array addition. For example:
$a4 = $a1 + $a2;
$a4 becomes a combination of $array1 and $array2. When used this way, the plus sign is referred to as the array union operator. If 2 arrays have the same keys, whether integer keys or string keys, the latter array’s duplicate value won’t show up in the union of the two, only the first array’s value with that key will be present.
If you try to add an array and a non-array though, the PHP engine will throw a fatal error, because the addition operator requires that both the operands (the expressions on either side of the plus sign) be of the same supported type.
That’s enough information to get you started using arrays. Later, we’re going to take a look at the vast number of built-in PHP functions that you can use with your arrays.
February 06 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on PHP Arrays
PHP variables are loosely-typed, so a variable’s type isn’t really defined until you assign a value to it. Prior to that, all variables have the special type ‘null’, which is just a way of saying no type and no value. Once you give a variable a value, it also gets a type. PHP supports 7 types, besides null, but for most of this title, we’re really only going to look at 4 of them:
int – these are your counting numbers
string – any sequence of characters inside single or double quotes
array – a set of things that can be referenced individually or as a group
boolean – true or false
In addition to those types, PHP also supports floats, objects, and resources and these get covered in detail later in this tutorial. But those first 4 types are the most important to learn here at the beginning, and will probably make up more than 90% of the variables you use in your everyday coding, at least for a while.
In order to determine a variable’s type, PHP provides a special function called ‘gettype’. Here it is in action:
echo gettype($var1); //assuming $var1 isn’t defined anywhere, this will print ‘NULL’
$var1 = ‘I am a string’;
echo gettype($var1); //prints ‘string’
$var1 = 55;
echo gettype($var1); //prints ‘int’
$var1 = array(55, 60);
echo gettype($var1); //prints ‘array’
$var1 = true;
echo gettype($var1); //prints ‘boolean’
{show output}
Now, if you have a variable of one type, but you need to use it a variable of a different type, you can do what’s called a cast. You do this by putting the desired variable type in parenthesis in front of the variable you want to convert. Here’s how it works.
Suppose I have a variable that’s an int:
$var1 = 56;
If I cast it to a string, it becomes:
$var2 = (string)$var1; //now the string ’56’
It’s now a string, made up of the characters 5 and 6. This is significant because text is stored differently than ints. They might print out the same on the screen, but to the server, it sees an int as the binary representation of the number 56. With strings though, it sees a separate binary representation for each character, and these have to be linked together in some way that preserves information about those characters’ order. So it takes a bit more memory to store the string ’56’ than the int 56.
If you want to cast your variable as an array, here’s what you do:
$var2 = (array)$var1;
In this case, it just takes $var1 and makes it the first value in a new PHP array, and assigns that array to $var2. We talk more about arrays in another video, but basically they’re just a way of holding sets of data together. And doing a type cast like this just makes a set with one item – the variable being cast.
Moving on, if you want to cast your variable as a boolean, you just do this:
$var2 = (bool)$var1;
-or-
$var2 = (boolean)$var1;
When converting an int to a boolean, in this case you’ll get true. In fact any int other than 0 will convert to true. Besides the int 0, other values that will convert to false are an empty string, an empty array, and a null. Everything else converts to true.
As far as converting things to ints, all you need to do is:
$var2 = (int)$var1;
or
$var2 = (integer)$var1;
PHP knows that int and integer mean the same thing. If you convert a boolean to an int, a value of true becomes 1, and a value of false becomes 0.
$var1 = true;
$var2 = (int)$var1; //$var2 is now 1
If you convert an array to an int, if the array is empty you get a 0, and otherwise you get a 1;
$var1 = array(56, 80);
$var2 = (int)$var1; //$var2 is now a 1
If you convert a string to an int, then if that string begins with a number, the int you convert to will have that number as its value
$var1 = ‘340,339,234’;
$var2 = (int)$var1; //$var2 is now 340
Notice that even though the number is written out as a string with commas representing the thousands and millions places, because those commas are non-numeric, the integer conversion stops at the first comma and only gives back the first 3 digits before the comma. And if the string doesn’t start with a numeral, even if there are numbers later in it, the converted value is a 0. One exception, by the way, is if the string starts with spaces followed by numbers. If that happens, the spaces get ignored and the numbers after them are used to create the integer.
Converting to a string from a boolean is simple. If your boolean is true, you get the string ‘true’. If your boolean is false, you get the string ‘false’.
Converting an array to a string is even simpler. No matter what the value of your array, whether it’s empty or not, the string representation is always the capitalized word ‘Array’.
February 06 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on PHP Variable Types
PHP variables can hold any type of data the language supports, and they don’t need to be declared before they are used. In programmer terms, we refer to PHP as a loosely-typed language.
All PHP variables begin with a $ and are followed by a sequence of characters. Valid characters are letters, numbers, and the underscore. However, a variable may not begin with a number. If it does, the PHP engine will see it and throw a parse error and your script won’t be able to run.
When your script runs, it gets read by the interpreter from top to bottom. A variable won’t have a value until it gets assigned one. Further down in the script you can access that variable’s value.
Assigning a literal value to a variable is pretty simple. You just write something like:
$var1 = ‘I am a variable’;
By the way, when I talk about literals, I mean like a literal 5 or a string inside of quotes. Literals, by themselves, are valid expressions in PHP. They don’t do anything, but they don’t break anything either.
{write ‘next line’; underneath first line}
In this case $var1 now holds the string of characters ‘I am a variable’ that were set inside the single-quotes.
Notice that the statement ends in a semi-colon. All PHP statements end in semi-colons. If you forget them, you’ll trigger a parser error and your script won’t run.
If you’re using an editor like I do, it’ll typically point out any mistakes like that for you. Different editors mark errors differently, but mine just displays a red wavy underline.
{show editor and point out mistake}
In the case of a missing semi-colon, notice the error is actually marked on the next line. This is because PHP ignores white-space. You could stick your semi-colon as far apart from your statements as you like really. So in this case, the error is I’ve started my next statement before closing the previous one.
Now, if you’re familiar with a more strictly-typed language, PHP’s looseness can look pretty strange. There is nothing wrong with suddenly changing my variable from one type to another.
$var1 = 5.8; //now it’s a float!
$var1 = true; //now it’s a boolean
$var1 = 1; //now it’s an int
And if I suddenly start using an undeclared variable as, for example, an array, PHP just creates an empty array in that variable’s place and then starts acting on it however I’ve told it to.
$var2[0] = 5; //$var2 is suddenly an array with key ‘0’ set to the value ‘5’
Likewise, if I use the increment operator – two plus signs together, PHP assumes I want an int, sets its value to 0, and then increments it like I asked, so I end up with the int ‘1’.
$var3++; //when I check it next time, $var3 will equal 1
PHP is so loosely typed that you can even mix operand types in some cases. If you’re unfamiliar with the terminology, an operand is an expression on one side of an operator, like a plus sign. So for instance, you can concatenate a number with a string. It just treats the number as though it were the string representation of it, and adds it to the string:
$var1 = 1;
$var2 = ‘Hello There! ‘ . $var1; //$var2 is now ‘Hello There! 1’;
It works the other way too. If you try to perform a math operation on a string, it just converts the string to a numeric representation and then proceeds with whatever math you wanted to do. The way it does this is by only looking at the beginning of a string. If there’s a number there, that’s the number it uses it as. If not, then it just gets used as a 0.
$var1 = ‘Hello’;
$var2 = 3+$var1; //$var2 is now 3
$var3 = ’12 cans of rice’;
$var4 = 5*$var3; //$var3 is treated as 12, so $var4 is now 5*12, which is 60
Mixing operand types only works in some cases. It depends on the types and it depends on the operator. We’ll look more at both variable types and operators in later videos.
It might look strange if you’ve ever coded with strict types, but it’s actually pretty freeing once you’re used to it. Of course, it makes it that much easier to make a mistake. If you have a variable called ‘$myWritable’, and you use it all throughout your script, but then in one place you accidentally misspell it as ‘$myWriteable’, PHP will simply assume you want a new variable, default its value to null, and then use it for whatever you tell it to. Unless you use it in a way that will specifically crash if the value is null, you won’t get an error. You’ll simply not get the results you expect, and it can be a pain to have to track it down and fix it.
February 05 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on PHP Variables
PHP includes a number of convenient built-in functions. These built-in functions are written in C, and are all faster than what you could accomplish with a custom function written in PHP.
The set of functions I want to introduce you to in this video all deal with your variables and what they are.
The first function is called ‘isset’. ‘isset’ will return true if you call it on a variable that has been assigned to a non-null value. Unlike most other PHP functions, isset is actually a language construct. For most purposes, there isn’t much distinction between it and the other built-in functions. However, it’s worth pointing out that you must invoke it on a variable, even one you haven’t yet declared. If you try invoking it on a string or an int or the return value of another function, your script will fail to execute, and even with error reporting enabled, you won’t see an error notice.
{show isset being called with a literal}
Generally mentioned in the same breath as ‘isset’ is the function ‘unset’. unset is also a language construct, and also cannot be called on anything other than a variable. All it does is clear a variable’s contents and remove it from memory. If you try accessing that variable again later, it’s value will report as null.
The last language construct in this set is the function ’empty’. In some sense you can think of it like the counterpart to isset. Again, it can only be called on a variable, but instead of telling you whether a variable is set, it tells you whether that variable evaluates to false. So, if you set a variable to either null, the empty string, the boolean false, an empty array, or the number 0 it will return ‘true’, because when PHP converts any of those to booleans they all evaluate to false. I know, the logic sounds a little backwards when I explain it that way, but that’s how it works. If you test a variable with any value that evaluates to true, ’empty’ returns false.
The next set of methods can tell you much more about what a variable actually is, and these are not language constructs, by the way. Whereas language constructs are the lowest-level elements of the PHP language, the rest of these functions (like most functions PHP provides) are built up from a combination of C code and the language constructs. As far as your everyday coding goes, if you use Zend Studio, as I do, it just means that they don’t get colored blue automatically when you type them. You could also invoke them on literal strings or ints, the return values of other functions or whatever, and not just actual variables, if you were so inclined.
Now, I’m going to go through these kind of fast, but one of the nice things about these functions is I can just introduce them by name and it’s obvious what they do. So, first we have is_array to test whether a variable is an array. is_object tests whether something is an object. is_resource checks for resources. We talk more about objects in a later chapter. You can use is_scalar to test for something that’s neither an array, a resource, nor an object. is_numeric tests for numbers, whether they’re ints or floats. If you just want to test for a float, you can use is_float or is_double (they’re exactly the same functions). If you just want to test for ints, you can use is_int, is_integer, or is_long (all 3 are exactly the same function). is_string tests for strings. is_boolean tests for booleans. There’s even a function to test for nulls called ‘is_null’. Functionally, is_null is the exact opposite of isset, except that it won’t crash your script to call it on a literal or on the return value of another function.
At this point you’ve probably noticed a pattern. If you just start searching for functions starting with the prefix ‘is_’ you’re going to find a whole lot more just like the ones I’ve mentioned.
{bring up PHPfr showing all functions with the ‘is_’ prefix}
Every different variable type has an ‘is’ function associated with it. And there are very useful ‘is’ functions to test for things like whether or not a particular constant has been defined, whether a particular directory is writable, whether an object is an instance of a particular class or sub-class, whether the filepath you’re working with represents a file that’s been uploaded from a form. The list isn’t exactly endless, but it’s pretty darn long. All of these functions perform some sort of test on your variable and return true or false depending on the test and the variable. The ones I’ve mentioned are probably the ones you’ll use the most, but they all have their place once in a while.
If you don’t want to run a true-false test for the type of a variable, but just want the variable directly, use ‘gettype’. It has 8 possible return values:
{bring up PHPfr page for ‘gettype’}
array
int
double – we usually call these floats, but it’s returned as ‘double’ for historical reasons
string
resource
object
boolean
null
February 04 2010 | Basics and Built-in PHP functions and PHP tutorial scripts and Schmategories | Comments Off on Basic Language Functions
PHP was initially envisioned as a way to get dynamic content onto a webpage. And to that end, the creators assumed their users would write a website in HTML, and then intersperse PHP code at different points within those pages in order to let them adjust to different situations. And it should be noted, PHP still works great for that.
But when PHP 3 was released, some engineer decided to add very simple, very basic object support. And it wasn’t even object support the way most object-oriented languages would describe it. Yes it was a way of keeping a collection of functions and variables inside a separate scope. But under the hood, it was really just associative arrays powering it all.
But surprisingly, a lot of PHP developers started playing with objects, and they liked some of the things they could do with them. So, over the years, PHP has started to look more like a traditional object-oriented language. Now, pretty much any design strategy you can accomplish with a mainstream OO language like C++ or Java, you can implement in PHP.
A question I hear a lot from people starting out with PHP, is “Does this look like a project where I should pursue an object-oriented approach?”
The answer depends on a number of factors.
The first point I should get across is that there is a performance penalty when you use objects in PHP. There is some overhead PHP needs to add in order to create objects, and if you were to design 2 separate websites that did the exact same thing, down to the last instruction, but one did it all procedurally, and the other used objects, the procedural site would be measurably faster.
So, when deciding whether to use objects, the first question you have to ask is what will you gain that makes the performance penalty, albeit a small one, worth it?
Well, first off, objects let you abstract out portions of your code. That means that you can have objects that pretty much take care of themselves, and when your code interacts with them, it doesn’t need to know exactly what they’re doing in order to use them. This means that if you want to change how one part of your project works, it can be decoupled from other parts to such a degree that those other parts won’t also have to be modified. At least, not in most situations.
The second advantage objects can infer is the ability to avoid code duplication. Code duplication can happen when you have particular tasks that get done many different times throughout your code. Now, some of the problems with duplication can be effectively dealt with by using custom functions. And functions don’t have the same overhead as objects. So if your project is small enough that, with a manageable number of functions you can avoid code duplication, then that’s probably the best approach. But when that list of functions becomes very difficult to manage, then much like organizing your computer’s files into folders, organizing your functions into class methods can make your development much easier.
The last advantage is that, once you get the hang of objects, it’s actually much easier for most programmers to envision their data and logic as distinct objects. And if it’s easier to understand how your application or website is built, then it will be easier to bring other people onto your project. So, whenever your project is going to be large enough that multiple people will be working on it, objects are almost always going to be worth the overhead.
February 02 2010 | Schmategories | Comments Off on When to use object-oriented versus procedural programming
« Prev - Next »