Archive for the 'PHP Programming Basics' Category
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
« Prev