I. Introduction to PHP

  • A PHP document will output only HTML.
  • If you have only PHP code in a file, you may omit the closing ?>. This can be a good practice, as it will ensure that you have no excess whitespace leaking from your PHP files (especially important when you're writing object-oriented code).
  • PHP commands ended with must a semicolon.

PHP

Including PHP in a File:
<?php
echo "Salem";
?>
Or
<?
echo "Salem";
?>

Result

Salem

Writing Comments

Description
// Denotes comments that only span on one line
# Another way of producing single-line comments
/*...*/ Everything between /* and */ is not executed, also works across several lines

PHP

<?php
echo "Salem Aleykum";
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>

Result

Salem Aleykum

II. Variables

  • You must place a $ in front of all variables.
  • Variable names, after the dollar sign, must start with a letter of the alphabet or the _ (underscore) character.
  • Variable names can contain only the characters a-z, A-Z, 0-9, and _ (underscore).
  • Variable names should not contain spaces.
  • Variable names are case-sensitive.
  • PHP also supports the bytes from 127 through 255 in variable names.

PHP

<?php
$My_Variable = "Introduction to PHP";
echo $My_Variable;
?>

Result

Introduction to PHP

Variable Scope

  • Local variables: Local variables are variables that are created within, and can be accessed only by, a function. One set of local variables is the list of arguments to a function.
  • Global variables: To access variables from global scope, add the keyword global.

PHP

Declare a global variable in a separate file:
<?php
global $The_Global_Variable;
?>

Then access it in another file:
<?php
$The_Global_Variable = "I am a global variable";
echo $The_Global_Variable;
?>

Result

I am a global variable
  • Static variables: A local variable inside a function that you don't want any other parts of your code to have access to, but you would also like to keep its value for the next time the function is called.
  • The next time the function is called, because $count has already been declared, the first line of the function is skipped.
  • If you plan to use static variables, you should note that you cannot assign the result of an expression in their definitions. They can be initialized only with predetermined values.

PHP

<?php
function test()
{
static $count = 0;
echo $count;
echo "
";
$count++;
}
test();
test();
test();
test();
test();
?>

Result

0
1
2
3
4
  • Superglobal variables: predefined variables known as superglobal variables, which means that they are provided by the PHP environment but are global within the program, accessible absolutely everywhere.
  • All of the superglobals (except for $GLOBALS) are named with a single initial underscore and only capital letters. Here is the complete list.

Constants

  • To declare a constant, use the define() function.
  • Then, to read the contents of the variable, you just refer to it like a regular variable (but it isn't preceded by a dollar sign).
  • Predefined Constants: PHP comes ready-made with dozens of predefined constants known as the magic constants. The names of the magic constants always have two underscores at the beginning and two at the end. Here is the complete list.

PHP

<?php
define("ROOT_LOCATION", "/usr/local/www/");
echo ROOT_LOCATION;
?>

Result

/usr/local/www/

III. Strings

  • PHP supports two types of strings that are denoted by the type of quotation mark that you use. If you wish to assign a literal string, preserving the exact contents, you should use single quotation marks (apostrophes).
  • In this case, every character within the single-quoted string is assigned to $Single_Quote_String. If you had used double quotes, PHP would have attempted to evaluate $My_Variable as a variable.
  • On the other hand, when you want to include the value of a variable inside a string, you do so by using double-quoted strings.
  • As you will realize, this syntax also offers a simpler option to concatenation in which you don't need to use a period, or close and reopen quotes, to append one string to another. This is called variable substitution.
  • String concatenation uses the period (.) to append one string of characters to another.

PHP

<?php
$My_Variable = "Introduction to PHP <br>";
echo $My_Variable;
$Single_Quote_String = 'This is a string declared with single quotes $My_Variable <br>';
echo $Single_Quote_String;
$Double_Quote_String = "This is a string declared with double quotes $My_Variable <br>";
echo $Double_Quote_String;
$Concatenated_String = '$My_Variable contains the follwing value: ' . $My_Variable;
echo $Concatenated_String;
$My_Variable .= $My_Variable;
echo $My_Variable;
?>

Result

Introduction to PHP
This is a string declared with single quotes $My_Variable
This is a string declared with double quotes Introduction to PHP
$My_Variable contains the follwing value: Introduction to PHP
Introduction to PHP
Introduction to PHP
  • To escape characters with special meaning add a backslash directly before to tell PHP to treat the character literally and not to interpret it
  • These special backslash-preceded characters work only in double-quoted strings. In single-quoted strings, the preceding string would be displayed.
  • Within single-quoted strings, only the escaped apostrophe (\') and escaped backslash itself (\\) are recognized as escaped characters.

PHP

<?php
echo "<pre>";
echo 'It\'s a beautiful day! <br>';
echo "He said:\n \"It's \ta \tbeautiful \tday!\" <br>";
echo 'He said:\n \"It\'s \ta \tbeautiful \tday!\" <br>';
echo "</pre>";
?>

Result

It's a beautiful day!
He said:
"It's a beautiful day!"
He said:\n \"It's \ta \tbeautiful \tday!\"

IV. Operators

Operators Description Example
Arithmetic + Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
** Exponentiation (or power)
$j + 1
$j - 1
$j * 11
$j / 4
$j % 9
++$j
--$j
$j**2
Comparison == Is equal to
!= Is not equal to
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal to
<> Is not equal to
=== Is identical to
!== Is not identical to
Because PHP is a loosely typed language,
if the two operands of an equality expression
are of different types, PHP will
convert them to whatever type makes
the best sense to it. A rarely used identity operator,
which consists of three equals signs in a
row, can be used to compare items without doing conversion.
See example below.
$j == 4
$j != 21
$j > 3
$j < 100
$j >= 15
$j <= 8
$j <> 23
$j === "987"
$j !== "1.2e3"
Logical && And
and Low-precedence and
|| Or
or Low-precedence or
! Not
xor Exclusive or
A lower precedence force a second
statement to execute if the first fails.
$j == 3 && $k == 2
$j == 3 and $k == 2
$j < 5 || $j > 10
$j < 5 or $j > 10
! ($j == $k)
$j xor $k
Assignment =
+=
-=
*=
/=
.=
%=
$j = 15 Equivalent to $j = 15
$j += 5 Equivalent to $j = $j + 5
$j -= 3 Equivalent to $j = $j - 3
$j *= 8 Equivalent to $j = $j * 8
$j /= 16 Equivalent to $j = $j / 16
$j .= $k Equivalent to $j = $j . $k
$j %= 4 Equivalent to $j = $j % 4
increment/decrement ++$x; Pre-increment
$x++; Post-increment
--$y; Pre-decrement
$y--; Post-decrement
$j = 0;
echo ++$j + 3;

PHP

<?php
$a = "1000";
$b = "+1000";
if ($a == $b) echo "1";
if ($a === $b) echo "2";
?>

Result

What should be the output?

V. Loops

For Loop

for (starting counter value; ending counter value; increment by which to increase) {
// code to execute goes here
}

for ($i = 1, $j = 1 ; $i + $j < 10 ; $i++ , $j++)
{
// code to execute goes here
}

The key is to distinguish commas from semicolons. The three parameters must be separated by semicolons. Within each parameter, multiple statements can be separated by commas.

PHP

<?php
for ($count = 1; $count <= 10; ++$count)
{
echo "Salem for the $count time <br>" ;
}
?>

Result

Salem for the 1 time
Salem for the 2 time
Salem for the 3 time
Salem for the 4 time
Salem for the 5 time
Salem for the 6 time
Salem for the 7 time
Salem for the 8 time
Salem for the 9 time
Salem for the 10 time

Foreach Loop

foreach ($InsertYourArrayName as $value) {
// code to execute goes here
}

While Loop

while (condition that must apply) {
// code to execute goes here
}

PHP

<?php
$count = 10;
while ($count > 1) {
echo "Salem <br>";
$count--;
}
?>

Result

Salem
Salem
Salem
Salem
Salem
Salem
Salem
Salem
Salem

Do..While Loop

do {
// code to execute goes here;
}
while (condition that must apply);

/

PHP

<?php
$count = 1;
do
echo "Salem for the $count time <br>";
while (++$count <= 12);
?>

Result

Salem for the 1 time
Salem for the 2 time
Salem for the 3 time
Salem for the 4 time
Salem for the 5 time
Salem for the 6 time
Salem for the 7 time
Salem for the 8 time
Salem for the 9 time
Salem for the 10 time
Salem for the 11 time
Salem for the 12 time

Break

if you have code nested more than one layer deep that you need to break out of, you can follow the break command with a number to indicate how many levels to break out of:

break 2;

VI. Conditional statements

If Statement

An else statement closes either an if...else or an if...elseif...else statement. You can leave out a final else if it is not required, but you cannot have one before an elseif; you also cannot have an elseif before an if statement.

PHP

<?php
if (condition) {
// code to execute if condition is met
}
elseif (another condition) {
// code to execute if this condition is met
}
else {
// code to execute if none of the conditions are met
}
?>

Result

Switch Statement

With switch statements, you do not use curly braces inside case commands. Instead, they commence with a colon and end with the break statement. The entire list of cases in the switch statement is enclosed in a set of curly braces, though.

PHP

<?php
switch (n) {
case x:
code to execute if n=x;
break;
case y:
code to execute if n=y;
break;
// add more cases as needed
default:
code to execute if n is neither of the above;
}
?>

Result

The ? (or ternary) Operator

PHP

<?php
$Variable = $Condition ?
"Value to return when true" :
"Value to return when false";
?>

Result

VII. Functions

The general syntax for a function is as follows:
function function_name([parameter [, ...]])
{
// Statements to execute
}

The first line of the syntax indicates the following:

  • A definition starts with the word function.
  • A name follows, which must start with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • The parentheses are required.
  • One or more parameters, separated by commas, are optional.
Function names are case-insensitive.

PHP

<?php

?>

Result

VIII. Arrays

  • Some arrays are referenced by numeric indexes; others allow alphanumeric identifiers.

Indexed arrays

  • Arrays that have a numeric index.
  • each time you assign a value to the array $Student, the first empty location within that array is used to store the value, and a pointer internal to PHP is incremented to point to the next free location

PHP

<?php
$Student[] = "Karim";
$Student[] = "Amel";
$Student[] = "Nour";
$Student[] = "Ahmed";
print_r($Student);
?>

Or
<?php
$Student[0] = "Karim";
$Student[1] = "Amel";
$Student[2] = "Nour";
$Student[3] = "Ahmed";
print_r($Student);
?>

Result

Array (
[0] => Karim
[1] => Amel
[2] => Nour
[3] => Ahmed
)

Associative arrays

  • Associative arrays reference the items in an array by name rather than by number.
  • The names (Karim, Amel, and so on) are called indexes or keys, and the items assigned to them (such as First Year Student) are called values.

PHP

<?php
$Student["Karim"] = "First Year Student";
$Student["Amel"] = " Second Year Student";
$Student["Nour"] = " Third Year Student";
$Student["Ahmed"] = " Fourth Year Student";
print_r($Student);
?>

Result

Array (
[Karim] => First Year Student
[Amel] => Second Year Student
[Nour] => Third Year Student
[Ahmed] => Fourth Year Student
)

Assignment Using the array Keyword

Using the format key => value. The use of => is similar to the regular = assignment operator, except that you are assigning a value to an index rather than to a variable.

PHP

<?php
$My_Array = array("Karim", "Amel", "Nour", "Ahmed");
print_r($My_Array);
echo "<br>";
$My_Second_Array = array("Karim" => "First Year Student",
"Amel" => "Second Year Student",
"Nour" => "Third Year Student",
"Ahmed" => "Fourth Year Student");
print_r($My_Second_Array);
?>

Result

Array (
[0] => Karim
[1] => Amel
[2] => Nour
[3] => Ahmed
)

Array (
[Karim] => First Year Student
[Amel] => Second Year Student
[Nour] => Third Year Student
[Ahmed] => Fourth Year Student
)

The foreach...as Loop

  • The foreach...as loop is especially for arrays: . Using it, you can step through all the items in an array, one at a time, and
  • When PHP encounters a foreach statement, it takes the first item of the array and places it in the variable following the as keyword; and each time control flow returns to the foreach, the next array element is placed in the as keyword.

PHP

<?php
$Students = array("Karim", "Amel", "Nour", "Ahmed");

foreach ($Students as $Student) {
echo $Student . "<br>";
}
echo "<br>";
$Students_Year = array(
"Karim" => "First Year Student",
"Amel" => "Second Year Student",
"Nour" => "Third Year Student",
"Ahmed" => "Fourth Year Student");

foreach ($Students_Year as $Student => $Year) {
echo $Student . " is a " . $Year . "<br>";
}
?>

Result

Karim
Amel
Nour
Ahmed

Karim is a First Year Student
Amel is a Second Year Student
Nour is a Third Year Student
Ahmed is a Fourth Year Student

Multidimensional arrays

  • Arrays that contain one or more other arrays.
  • You can directly access a particular element of the array by using square brackets: $array[0][1].

PHP

<?php
$University_Staff = array(
'Students_Year' => array("Karim" => "First Year Student",
"Amel" => "Second Year Student",
"Nour" => "Third Year Student",
"Ahmed" => "Fourth Year Student"),
'Teachers' => array("Mohamed" => "DSA",
"Hassan" => "DB",
"Ali" => "OS",
"Omar" => "AI"),
'Courses' => array("DSA" => "Data Structure",
"DB" => "Data Base",
"OS" => "Operating System",
"AI" => "Artificial Intelligence")
);
print_r($University_Staff);
echo "<br>";
echo $University_Staff['Courses']['DSA'];
?>

Result

Array (
[Students_Year] => Array (
[Karim] => First Year Student
[Amel] => Second Year Student
[Nour] => Third Year Student
[Ahmed] => Fourth Year Student
)
[Teachers] => Array (
[Mohamed] => DSA
[Hassan] => DB
[Ali] => OS
[Omar] => AI
)
[Courses] => Array (
[DSA] => Data Structure
[DB] => Data Base
[OS] => Operating System
[AI] => Artificial Intelligence
)
)
Data Structure

Array functions

Here the complete list.
Function Description Example
is_array To check whether a variable is an array. $Students = array("Karim", "Amel", "Nour", "Ahmed");
$Another_Variable = "Anything";
if (is_array($Students)) echo "Yes, it's an array";
else echo "No, it's not an array";
count To count all the elements in the top level of an array.
To know how many elements there are altogether in a
multidimensional array, you can use count($fred, 1);
The second parameter is optional and sets the mode to use.
It should be either 0 to limit counting to only the top level
or 1 to force recursive counting of all subarray elements too.
echo count($Students);
sort It will act directly on the supplied array rather than
returning a new array of sorted elements. It returns TRUE
on success and FALSE on error and also supports a few flags: sort($Students, SORT_NUMERIC); OR sort($Students, SORT_STRING);
To sort an array in reverse order using the rsort function:
rsort($Students, SORT_NUMERIC); OR rsort($Students, SORT_STRING);
sort($Students);
print_r($Students);
explode can take a string containing several items separated
by a single character (or string of characters) and
then place each of these items into an array.
The first parameter, the delimiter, can be several characters.
$URL = "https://ensia-ai.github.io/Web_Development_2023/";
$temp = explode("/", $URL);
print_r($temp);
extract To turn the key/value pairs from an array into PHP variables.
If the variables were sent using the GET method, they will be
placed in an associative array called $_GET; if they were sent
using POST, they will be placed in an associative array called $_POST.
Be careful with this approach, though, because if any extracted variables
conflict with ones that you have already defined, your existing values
will be overwritten. To avoid this possibility, you can use one of the
many additional parameters available to this function, like this:
extract($_GET, EXTR_PREFIX_ALL, 'fromget');
In this case, all the new variables will begin with the given prefix
string followed by an underscore.
extract($Students_Year);
echo "Karim is a $Karim<br>";
echo "Amel is a $Amel<br>";
echo "Nour is a $Nour<br>";
echo "Ahmed is a $Ahmed<br>";
compact The inverse of extract.
Note how compact requires the variable names to be supplied in quotes,
not preceded by a $ symbol. This is because compact is looking for a
list of variable names, not their values.
$temp= compact("Karim","Amel","Nour","Ahmed");
print_r($temp);