Oct
01
2008

PHP Basics: Operators

This is the largest Blog post yet, theirs lots of information about operators and some of it gets complex. Their are 10 Operator categories covered in this post, so read and lean.

This is a PHP 5 Zend Certification reading aid with the purpose to cover topics that may not be covered in the Study Guide. Good Luck!

Their are many types of PHP Operators such as:

  • Assignment Operators assigns data to variable ($variable = “data”;)
  • Arithmetic Operators - doing math ($sum = (5 + 5;) * 2); )
  • String Operators - joining two strings ( $fullname = $firstname.’ ‘.$lastname; )
  • Comparison Operators - Comparing 2 pieces of data ( if($x > $y) )
  • Logical Operators - performing logical operations to Boolean (?)
  • Includeing some more complex operators:

  • Bitwise Operators - manipulates bits useing boolean
  • Error Control Operators - suppressing errors
  • Execution Operators - execute system commands
  • Arithmetic Increment/Decrease Operators - increase or decrease numerical data
  • Type Operators - identify objects
  • Assignment Operators

    If your reading this blog, you should know this. Its the complex term for allocating data to a variable! The basic assignment operator is “=“. You may think of it as “equal to”. Dont! It really means that the left operand gets set to the value on the right.

    $operand = "this text";

    More advanced assignment operator is using a full stop to merge one variable to anouther like such:

    $b = "Hello ";
    $b .= "There!"; // sets $b to "Hello There!"

    Arithmetic Operators

    These operators allow you to write a PHP Script to act as a calculator, to work out Maths on your behalf. The operators are simple for addition (+) and subtraction (-) the operators for Multiplication (*) and Division (/) are not as simple.
    Addition:

    $addition = 1 + 3.5;
    //or useing variables
    $addition2 = $3.5 + $variable;
    //Minipulate Left Variable
    $a = 3;
    $a += 5; //same as 3+5

    Subtraction:

    $subtraction = 3.5 - 1;
    //or useing variables
    $subtraction2 = $3.5 - $variable;
    //Minipulate Left Variable
    $a = 3;
    $a -= 2; //same as 3-2

    Multiplication:

    $multiplicationn = 3.5 * 2;
    //or useing variables
    $multiplication2 = $3.5 * $variable;
    //Minipulate Left Variable
    $a = 3;
    $a *= 5; //same as 3*5

    Division:

    $division = 3.5 / 2;
    //or useing variables
    $division2 = $3.5 / $variable
    //Minipulate Left Variable
    $a = 4;
    $a /= 2; //same as 4/2

    String Operators

    As we have discussed in assignment operators strings can be merged with each other like such:

    $b = "Hello ";
    $b .= "There!"; // sets $b to "Hello There!"

    This is not the only way to glue two strings together as PHP allows more full stop fun like such:

    $string = "Hello " . "World"; //Outputs: Hello World
    //Useing variable works too
    $string = $sting . ' I Code PHP'; //Outputs: Hello World I Code PHP

    So that’s great, You can add data to more data but remember never use the + to try and merge strings as that can only be used in Arithmetic! You have to use full stop . !!

    Comparison Operators

    These are majority used in conditional statements, comparing one variable to another variable. They are highly useful and if you have never seen them before, you should probably code more in PHP before booking the test.
    $a == $b True if values of $a and $b are the same.
    $a === $b True if values and data type of $a and $b are the same.
    $a != $b True if $a does not equal $b
    $a <> $b True if value of $a does not equal $b
    $a !== $b TRUE if $a is not equal to $b, or they are not of the same type.
    $a < $b True if $a is less then $b
    $a > $b True if $a is more than $b
    $a <= $b True if $a is less then or equal to $b
    $a >= $b True if $a is more than or equal to $b

    Logical Operators

    These are majority used in conditional statements, comparing one variable with anouther. They are highly useful and if you have never seen them before, you should probably code more in PHP before booking the test. (I think I’m repeating myself).
    $a and $b TRUE if both $a and $b are TRUE. (or $a && $b)
    $a or $b TRUE if either $a or $b is TRUE. (or $a || $b)
    $a xor $b TRUE if either $a or $b is TRUE, but not both.
    ! $a TRUE if $a is not TRUE.

    Bitwise Operators

    Bitwise Operators, are not my speciality.. I will try try and learn and teach at the same time. (/fail).
    The Zend Study Guide sucks at explaining this!

    Bitwise is binary math. It uses Bit’s which can only be 0 and 1. It also uses bytes, bytes are made up of bit’s and can have up to the value of 255 (if a byte is 255 that means every bit is 1). Therefore 1 Byte is 8 Bit’s.. I understand this from (http://www.litfuel.net/tutorials/bitwise.htm) they also talk about a byte repersenting values 128, 64, 32, 16, 8, 4, 2, 1 (place values) and bits the 0 and 1 are asigned to these to give the result… Dont take my word for it, read!
    The Operators

    Example Name Result
    $a & $b And Bits that are set in both $a and $b are set.
    $a | $b Or Bits that are set in either $a or $b are set.
    $a ^ $b Xor Bits that are set in $a or $b but not both are set.
    ~ $a Not Bits that are set in $a are not set, and vice versa.
    $a << $b Shift left Shift the bits of $a $b steps to the left (each step means “multiply by two”)
    $a >> $b Shift right Shift the bits of $a $b steps to the right (each step means “divide by two”)

    The And Operator
    This checks to see what two numbers have in common in binary, what do 9 and 10 have in common?

    $a =	 9;
    $b =	10;
    echo $a & $b;

    The output is 8, as this is the number converted into bits that matches the place value 8. This means that 8 is output!

    The OR Operator
    This compares two numbers and adds up the place values of both of them.

    $a =	 9;
    $b =	10;
    echo $a | $b;

    The output of this is 11! this is because $a matches place values 8 and 1 whilist $B matches place values 8 and 2. The sum of 8+1+8+2=11 …. Good fun!

    The XOR Operator
    This adds up the place values that one has and the other one hasent!

    $a =	 9;
    $b =	10;
    echo $a ^ $b;

    Both $a and $b share the 8 bit, we dont want that one, we just want the 2 bit and the 1 bit that they each have set but don’t share. Soooo 2+1 = 3

    The NOT Operator
    The NOT operator compares two numbers, depending on where the not is applied it tells you what placevalues it has which the otherone does not.

    $a =	 9;
    $b =	10;
    echo $a & ~$b;

    The above code will tell us the sum of the place values that are in $a but that are not in $b. The answer is 1 as they both have place values 8 so thats not counted, $b has place value 2 but that’s where the NOT is applied and $a has place value of 1 where $b does not.

    Bit Shifting Operator
    This moves the place value two places to the left or right

    $a =	 16;
    echo $a << 2;

    The output of this is 64 (same as 16 X 2 = 32 x 2 = 64) this is due to the place value 16 has been shifted left to 32 then 64.

    More Info on Bitwise Operators:
    http://www.litfuel.net/tutorials/bitwise.htm This is where I learned the basics, knowledge of this is needed but I presume do not make a large feature in the PHP Test as binary is not used much at all in PHP Programming.

    Error Control Operator

    If you expect a script to output errors every now and then stick @ before it is executed, this will suppress the error messages they are output into variable $php_errormsg each error write over the previous.

    //Suppressing error, then outputting it how you wish.
    $file = @file ('non_existent_file') or die ("Failed opening file: error was '$php_errormsg'");
     
    // this works for any expression, not just functions:
    $value = @$cache[$key]; 
    // will not issue a notice if the index $key doesn't exist. Nor kill the script

    Execution Operators

    Did you know PHP can execute shell commands? Well it can using backticks (“) if safe mode is enabled though its more complex. This is great as you can send commands to your computer to run other scripts, a example could be YouTube sending a video to computer for conversion.

    $output = `ls -al`;
    echo "$output";

    The above code prints the directory listing.

    Arithmetic Increase/Decrease Operators

    These operators increase or decrease the operand by one. One is the only value that it can be increased or decreased off this is done by using– to minus and ++ to add like such:

    $a = 1;
    //a variable is set to one
    echo ++$a; //Increase - Outputs 2, $a is equal to 2
    echo --$a; //Decrease - Outputs 1, $a is equal to 1

    Easy right? But because PHP is so great it adds some complexity for those who want it. If you put the switch the operand from the right of the operator to the left it does the same but different as such:

    $a = 1;
    //a variable is set to one
    echo $a++; //Increase - Outputs 1, $a is equal to 2
    echo $a--; //Decrease - Outputs 2, $a is equal to 1

    As you can see if the operator is placed after its operand it will return the unchanged value, and then increase/decrease the variable for later use.

    Type Operators

    Their is not much to write about this apparently, Type Operator checks to see if a variable has been is an instantiated object of a certain. This is done by using the PHP function instanceof.

    class MyClass
    {
    }
     
    class NotMyClass
    {
    }
     
    $a = new MyClass;
     
    var_dump($a instanceof MyClass); //Outputs True
    var_dump($a instanceof NotMyClass);//Outputs False

    The end of Operators!

    Well, I am fed up of operators I can presume that you are now also bored of operators. Their are many types and they do a vast range of things.

    The Basic requirements for the PHP 5 Zend Certification Test in my opinion will lie in the basic operators: Assignment Operators, Arithmetic Operators, String Operators, Comparison Operators, Logical Operators Error Control Operators.
    I also presume their will be some bitwise operators in their too, just because binary annoys me.

    I hope you have learnt something from this blog, as I know I have… When (not if) you find a mistake in my blog dont frett to comment!

    You also have the responsibility to increase my knowledge of operators, so if theirs anything I have missed? Then comment bellow.

    Much Thanks
    Adam

    Share and Enjoy:
    • Digg
    • del.icio.us
    • Facebook
    • Mixx
    • Google
    • LinkedIn
    • Live
    • StumbleUpon
    • Technorati
    • TwitThis

    No Comments »

    RSS feed for comments on this post. TrackBack URL

    Leave a comment

    WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS