PHP Syntax Basics (For WordPress Students!)

 Conditional Statements:  

if ( condi­tion ) {

//do stuff

}

elseif ( condi­tion 2 ) {

//do stuff

}

else {

//do stuff

}

//alternative syntax

if ( condi­tion ) :

//do stuff

elseif ( condi­tion 2 ) :

//do stuff

else :

//do stuff

endif;

//ternary operator

// (is true) ? yes : no;

echo ( is_user_logged_in() ) ?

'Hello user' : ‘You are not logged in’;

 Loops:  

while( condition ){

//do stuff

}

//repeats for each item in array

foreach( $array as $value ){

//do stuff

}

Variables

$myVar = ‘some value’;

 Arrays:  

//create empty

$myarray = array()

//create numbered array with many items

$myarray = array( ‘thing’, ‘thing’, ‘thing’);

//create associative array with many items

$myarray = array(

     ‘thing1’ => ‘value’,

     ‘thing2’ => ‘value’,

     ‘thing3’ => ‘value’,

);

//multidimensional array

$myarray = array(

     ‘item1’ => array(

                  ‘sub-item’ => ‘value’,

                  ‘sub-item’ => ‘value’,

                  ‘sub-item’ => ‘value’,

     ),

     ‘item2’ => array(

                  ‘sub-item’ => ‘value’,

                  ‘sub-item’ => ‘value’,

                  ‘sub-item’ => ‘value’,

     ),

);

//create item in numbered array

$myarray[] = value;

//create item in associative array

$myarray[‘key’] = value;

 Functions:  

//define the function

function name( $arg, $arg ){

   //do stuff

}

//calling the function

name(value1, value2);

Operators:

Incremental

++

 Add one

--

Subtract one

+=10

Add 10 (or any number)

Assignment

=

Set it equal to

Comparison

==

Check for equality

>

Greater Than

<

Less Than

>=

Greater or equal

<=

Less or equal

!=

Not equal to

Logic

AND

returns true if both are true

OR

either or both are true

XOR

either but not both are true

&&

like AND (higher precedence)

||

like OR (higher precedence)

!

not true (negates argument)