PHP Basic Syntax

PHP Basic Syntax

Sums up the basic syntax of PHP language necessary to be able to write simple PHP applications.
cover

What is PHP? 

  • PHP (Hypertext Preprocessor) is a interpreted scripting language written in C and mostly used in Web Development. 
  • the most popular language for web development to this day
  • over 80% of all websites are written in PHP, including Facebook, Wikipedia, Yahoo, ...
  • open-source
  • PHP can run on freehostings
  • functional, procedural and also object-oriented 

Syntax 

PHP script starts with <?php and ends with ?>

(?> at the end of the file is not necessary if the whole script is in PHP) 

This can be used to separate HTML code from PHP script: 

<p>some html code <?php echo "some php code"; ?> and html code again</p>

Variable names always starts with $ whether we declare it, initialize it or call it. 

$variableName = 5;

PHP is dynamically typed, which means that the data type of the variable is assigned automatically and dynamically. 

$var = 5; // int
$var = "Hello, world"; // string
$var = 5/3; // float

Variable names can be also made dynamically. 

$foo = 123;
$var = "foo";

$$var = 55; // $foo = 55

Constants can be defined in 2 ways. 

const BAR = "something";
define("BAR", "something"); // global way (old school)

PHP also has some Magic constants . 

__FILE__      // The current line number of the file.
__LINE__      // The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__       // The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__  // The function name.
__CLASS__     // The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__METHOD__    // The class method name.
__NAMESPACE__ // The name of the current namespace.
__TRAIT__     // The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).

Or can work with certain variables from outside sources like HTTP requests (more about Superglobals here). 

$_GET    // Array of URL parameters.
$_POST   // Array of variables passed to the current script via the HTTP POST method.
...

String in PHP can be written in both single or double quotes. 

$str1 = "This is string";
$str2 = 'This is also string';

 Arrays:

// initialization
$arr = array();
$arr = []; // PHP 5.4+

// array of 3 strings
$arr = new array(
   "first",
   "second",
   "third"
); 
// alternatively (PHP 5.4+)
$arr = [
   "first",
   "second",
   "third"
]; 

echo $arr[2]; // prints "third"

// 2D array
$arr = [
   [1, 2, 3]
]; 

// associative array
$arr = [
   'key1' => [1, 2, 3]
]; 

echo $arr['key1'][1]; // prints "2" ("key1" is a key, not a value)

Variable comparison:

$a == $b // compares values
$a === $b // compares values and type
$a != $b
$a < $b
$a <= $b
$a > $b
$a >= $b

Control statements

Branching - if/elseif/else, switch

/****** IF-ELSEIF-ELSE ******/
if ($a > $b)
    echo "a is bigger than b";
elseif ($a == $b)
    echo "a is equal to b";
else
    echo "a is smaller than b";

/****** SWITCH ******/
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
        echo "i equals something else";
}

Loops - while, for, foreach, break, continue

// Prints nothing
$i = 10;
while ($i < 10) {
    echo $i++;
}

// Prints 10
$i = 10;
do {
    echo $i++;
} while ($i < 10);

// Prints 1 to 10
for ($i = 1; $i <= 10; $i++) {
    echo $i;
}
$arr = [
    'k1' => 50,
    'k2' => 150,
    'k3' => 1550,
];

foreach ($arr as $key => $value) {
    echo "Key $key equals to $value";
}

Above foreach code prints:

Key k1 equals to 50 
Key k2 equals to 150 
Key k3 equals to 1550 

Functions

function add($a, $b) {
    return $a + $b;
}

echo add(1, 2); // prints "3"

Functions can have variable amount of arguments:

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4); // can add how many we want

Basic PHP built-in functions

isset($a); // returns TRUE if $a is defined, FALSE otherwise
empty($a); // returns TRUE if $a is defined but has empty value (0, "", NULL), FALSE otherwise
unset($a); // deletes variable
is_numeric($a); // returns TRUE if $a is a number, FALSE otherwise
is_bool/string/integer/float/array/object($a); // similar to is_numeric
count($a); // returns the number of array $a elements

include('file'); // loads and executes external file, throws warning if doesnt exist
include_once('file'); // same as above but won't do anything if the file was included already
require('file'); // loads and executes external file, throws error if doesnt exist
require_once('file'); // same as above but won't do anything if the file was included already

 

In case of any question or comment regarding this article, please, contact us directly via our Facebook page.