PHP Syntax Reference


This is partial list of PHP syntax and control structures that i’ve put together for my reference. It covers a lot of entry level examples.

Basic function reference is available here.

The full official PHP manual is available here.

Comments:

<?php

// single line comment

/* This is a multiline comment.
technically this is all that is required
but most people will use additional
formatting as shown below. */

/*
* This is the commenting style that you will see in WordPress core files.
* The extra *'s make it easier to read when scrolling through the text.
* 
*/

?>

Additionally it is common to show categories and sub-categories with the following:

<?php

//======================================================================
// CATEGORY LARGE FONT
//======================================================================

//-----------------------------------------------------
// Sub-Category Smaller Font
//-----------------------------------------------------

/* Title Here Notice the First Letters are Capitalized */

?>

WordPress has a whole manual dedicated to proper documentation which can be found here: WordPress PHP Documentation Standards. It is based on phpDocumentor.

Echo + Print

<?php
    echo "This text will be printed";
    print "This text will be printed";
    // This is a single line comment
?>

What is the difference between echo and print? The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print. (Source w3schools)

Variables

<?php
/*
* Variables are declared with the $ symbol and
* the name of the variable. Name can be anything.
* Variables can then be called later with other functions.
*/

  $myName = "Nick";

//This will print the text "Nick"
echo $myName;

?>

Strings and Numbers

Strings: Are encapsulated in quotes and are taken as a whole. A string of text.

Numbers: Are plain numbers that will be calculated if they are part of an equation or returned as a numeric value.

** In PHP the numbers 1 and 0 are interpreted as a Boolean (true|false). So for example the math function rand(0,1) can assign a random true or false value to a variable.

<?php

echo "My name is Nick."
// This will print "My Name is Nick."

echo 4*5;
// This will print "20"

echo "4*5";
// This will print "4*5" as the equation is represented as a string.

?>

Comparison Operators

>  Greater than

<  Less than

<=  Less than or equal to

>=  Greater than or equal to

==  Equal to (values are equal)

=== Equal to (both values and variable types are equal Source)

!=  Not equal to

Shorthand

$i++  is shorthand for  $i=$i+1. It adds 1 to the variable (usually in an iteration of a loop)

If Statements

Check to see if the condition is true, and if it is run the code.

<?php
  $age = 55;

  if( $age >= 21 ) {
    echo "You can drink!";
  }
?>

Falling Through

<?php
$i = 2;

if ($i == 1 ||
    $i == 2 ||
    $i == 3) {
 echo '$i is somewhere between 1 and 3.';
}

// Will print "$i is somewhere between 1 and 3."
?>

 

If/Else Statements

If condition is not true, the else code will run.

<?php
  $name = "James";

  if ($name == "Simon") {
    print "How are you Simon";
  }
  else {
    print "Who are you?";
  }
?>

If/ElseIf/Else Statements

Checks the conditions in order. Will run the code for the first statement that is true, or if none of them is true will run “else”.

<?php
    $myName = "Susan";
    $myAge = 29;
    
    if ($myName == "Nick"){
        echo "You are the king of the world!";
        }
        elseif ($myAge == 29){
            echo "You may not be Nick, but you are his age";
            }
        else {
            echo "You are not Nick. I'm sorry...";
            }
    
?>

Switch Statements

Switch statements are very similar to if/elseif/else statements. If a condition is true is executes a block of code.

<?php
    switch (2) {
        case 0:
            echo 'The value is 0';
            break;
        case 1:
            echo 'The value is 1';
            break;
        case 2:
            echo 'The value is 2';
            break;
        default:
            echo "The value isn't 0, 1 or 2";
    }
    ?>

Switch statements can be used to check the value of variables. If the condition evaluates to true the code block will run and the “break” will exit the switch statement. Otherwise the next case block will run.

<?php
$pizza = "Pepperoni";

switch ($pizza) {
    case 'Pepperoni':
        echo "Yummy.";
        break;
    default:
        echo "Gross";
}

// This will print "Yummy."
?>

Falling Through

Allows multiple cases to run the same code block on evaluation.

<?php
    $i = 3;
    
    switch ($i) {
        case 0:
            echo '$i is 0.';
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            echo '$i is somewhere between 1 and 5.';
            break;
        case 6:
        case 7:
            echo '$i is either 6 or 7.';
            break;
        default:
            echo "I don't know how much \$i is.";
    }

// Will print "$i is somewhere between 1 and 5."
    ?>

Arrays

An array is a list that is named with a variable. Here is a simple example:

<?php
$groceries = array("Eggs", "Bacon", "Bagels", "Cheese");
?>

**array() is actually a predefined function

Arrays accept strings and integers. Items must be separated by comma: ,

Items in arrays are numbered starting at 0. This is important to remember as it is not intuitive.

Echo

You can print an item from an array with the following:

<?php
    $week = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

    echo $week[2]; //can also use curly braces

//This will print "Wednesday".
?>

**You can substitute the brackets with curly braces {} and it will also work. They are interchangeable.

Modify Element

<?php
$colors = array("red", "blue", "yellow");

echo $colors[0];
// outputs "red"

$colors[0] = "green";

echo $colors[0];
// outputs "green"
?>

Delete Element

You can delete elements from the array with the following:

<?php
  $colors = array("red", "blue", "green");
  unset($colors[1]);

// This will remove "blue" from the array
?>

Loops

For

The for loop, is a loop with a predefined beginning and end. It has the following basic structure:

for (start, end, each iteration) {

do the following

}

 

<?php
for ($i = 0; $i < 5; $i++) {
    echo $i;
}
// echoes 012345
?>

This tells us that the loop starts with the condition that $i=0, and will keep going as long as $i is less than 5. The loop evaluates the condition before performing the action. On the seventh iteration of the loop when $i=5 the loop will not run another time because variable $i is not smaller than 5. Lastly the 3rd instruction in the conditions says to add 1 to $i with every loop.

ForEach

ForEach loop is used in conjunction with arrays. It will go over each item in the array and execute the code for each item in order.

<?php
          $langs = array("JavaScript",
          "HTML/CSS", "PHP",
          "Python", "Ruby");
        
          foreach ($langs as $lang) {
              echo "<li>$lang</li>";
          }
        
          unset($lang);
        ?>

The ($langs as $lang) condition is where we are defining the name of the individual items in the array as a variable. The unset ($lang) at the end is destroying the variable $lang as it has served it’s purpose and is no longer needed.

While

Unlike a for loop which has a predefined beginning and end, a while loop will continue as long as the condition is true. This allows the loop to run for an undetermined amount of time. It takes the following format:

while (this condition is true) {
loop this code
}
<?php
$the_count = 1;

while ($the_count < 5){
	    
    echo "The count is less than 5. It is currently {$the_count}.";
    $the_count ++;
    echo "We added 1 to the count. Now it is {$the_count}.";
	}
    echo "<p>The count is now 5. The loop has stopped running.</p>";
    ?>

It is very important not to create an infinite loop. An example of an infinite loops would be any loop where the condition will always evaluate to true. For example if our condition was 2 > 1 then the loop will never end. We have no way to make this statement false.

Also note that PHP will always run in order. So for example our echo statement above The count is now above 5 will not run until the loop has completed. Additionally inside the loop it will take each item in order. So it will display the count, then it will add 1, then it will display the new count. It does not evaluate everything in the {} simultaneously.

Also note that we have temporarily changed the value of our variable $the_count, but as soon as the page reloads $the_count will revert to 1. To store a variable within a session use the PHP predefined variable $_SESSION (php.net, stackoverflow)

There is an alternative syntax for while loops.

while(cond):
   // looped statements go here
endwhile;

Some people think this is more readable when embedded in HTML.

Do While

In the While loop, the loop checks the condition before each iteration of the code. A Do While loop checks the condition after each iteration before looping back. This means that a While loop can be skipped entirely if the condition is not met, whereas a Do While loop will execute at least once. This means that the loop condition can depend exclusively on code within the loop’s body.

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
?>

All we are really doing here is putting the condition at the end of the loop with while. In the example above the condition is false ($i is not greater than 0) but the code will still run 1 time. However the loop will end after the first iteration.

<?php
    $rollcount = 0;
        
    do {
        $rollcount ++; //Adds 1 to rollcount
        $roll = rand(1,6); //Picks a random number 1-6
        echo $roll; //displays random # 1-6
    }
    while ($rollcount <= 10); //endloop when rollcount reaches 10
    
    ?>

 Classes

Classes allow us to create a set of variables and functions as a group which can then be called together for repetitive tasks, such as creating a new user. A basic class will look like this

class Classname {

}

and can then be called like this

$obj1 = new Classname();

Everything in the classes {} is the class definition  and will include variables.

These variables are the classes Properties.

A couple example variables would be:

class Animals {
  public $count;
  public $type;
}

another example of a class with a definition:

class Person {
  public $firstname;
  public $lastname;
  public $age;
}

Now that we have a class with properties we can create instances of the class in a variable

$dog = new Animal(); //we have created a new instance of the animal class inside a variable named $dog



/* Now that we have created an instance of our class we can assign values to the variables

that are associated with this class */

$dog->count = 5;

$dog->type = "Canine";



// Then we can output them

print $dog->count; //5

print $dog->type; //Canine

Constructor

We use the constructor to create objects.

public function __construct($prop1, $prop2) {
  $this->prop1 = $prop1;
  $this->prop2 = $prop2;
}

New things here are the public keyword and the arrow notation.

We are creating a method (a function bound to a class).

The constructor method must be called.     __construct()

<!DOCTYPE html>
<html>
	<head>
	  <title>Reconstructing the Person Class</title>
      <link type='text/css' rel='stylesheet' href='style.css'/>
	</head>
	<body>
      <p>
        <?php
        class Person {
            public $isAlive = "true";
            public $firstname;
            public $lastname;
            public $age;
            
         public function __construct($firstname, $lastname, $age) {
        $this->firstname = $firstname;  //we do this so that when we echo or print this later we can name this property as seen below
        $this->lastname = $lastname;
        $this->age = $age;
        
    }    
}
        
            $teacher = new person("boring","12345", 12345);
            $student = new person("Jane", "Fonda", 15);
            
        
        echo $teacher->age; //12345
        echo $student->age; //15
        
        ?>
      </p>
    </body>
</html>

The __construct() function is a special function which is called when a new object is created using the new keyword.

The $this keyword is used if you want to access a property in a class.

Methods

Methods are functions bundled into objects.

public function funcname($optionalParameter) {
  // Do something
}

Here is an example of new method called greet()

<?php
        class Person {
            public $isAlive = "true";
            public $firstname;
            public $lastname;
            public $age;
        
 
        public function __construct($firstname, $lastname, $age) {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
        $this->age = $age;
        }
        
        public function greet(){
        return "Hello, my  name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";    
        }
           
}
        
        $teacher = new person("Jim","Weber", 56);
        $student = new person("Jane", "Fonda", 15);
            
        
        echo $teacher->age; //12345
        echo $student->age; //15
        echo $teacher->greet();
        echo $student->greet();
        
        ?>

 

+ There are no comments

Add yours