You are on page 1of 98

We can identify an

array
by position
(called indexed arrays)

$person[0] = ‘Edison’;
$person[1] = ‘Wankel’;
$person[2] = ‘Crapper’;
... or by name (a string)
(called associative arrays)

$creator[‘Light bulb’] = ‘Edison’;


$creator[‘Rotary Engine’] = ‘Wankel’;
$creator[‘Toilet’] = ‘Crapper’;
What’s the output?

$foo = ‘bar’;

$arr[‘bar’] = ‘good’;
$arr[‘$foo’] = ‘morning’;

echo $arr[‘bar’];
echo $arr[“$foo”];
The array() construct
creates an array

// Indexed array
$person = array(‘Edison’, ‘Wankel’, ‘Crapper’);

// Associative array
$creator = array(‘Light bulb’ => ‘Edison’,
‘Rotary Engine’ => ‘Wankel’,
‘Toilet’ => ‘Crapper’);
PHP 5.4 offers a new
shorter way to create arrays

// Indexed array
$person = [‘Edison’, ‘Wankel’, ‘Crapper’];

// Associative array
$creator = [‘Light bulb’ => ‘Edison’,
‘Rotary Engine’ => ‘Wankel’,
‘Toilet’ => ‘Crapper’];
The range() function creates
an array of consecutive integer or
character values between two values

$numbers = range(2, 5);


// $numbers = [2, 3, 4, 5];

$letters = range(‘a’, ‘z’);


// $letters holds the alphabet

$reversedNumbers = range(5, 2);


// $reversedNumbers = [5, 4, 3, 2];
What’s the output?

$letters = range(‘z’, ‘a’);

echo $letters[4];
The print_r() intelligently displays
what is passed to it
$a = [‘name’ => ‘Fred’,
‘age’ => 35,
‘wife’ => ‘Wilma’];
echo $a;
print_r($a);

Array
Array
(
[name] => Fred
[age] => 35
[wife] => Wilma)
We can also use var_dump()
$a = [‘name’ => ‘Fred’,
‘age’ => 35,
‘wife’ => ‘Wilma’];
var_dump($a);

array(3) {
[“name”]=>
string(4) “Fred”
[“age”]=>
int(35)
[“wife”]=>
string(5) “Wilma”
}
To insert more values
into the end of an existing
indexed array, use the []
syntax

$family = [‘Fred’, ‘Wilma’];

$family[] = ‘Pebbles’;
// [‘Fred’, ‘Wilma’, ‘Pebbles’]
What’s the output?

$family = [‘Fred’, ‘Wilma’];

$family[] = ‘Pebbles’;
$family[] = ‘Dino’;
$family[] = ‘Baby’;

echo $family[4];
PHP 7.1 offers array
destructuring feature

$arr = [10, 20, 30];


[$a, $b, $c] = $arr;

echo $a; // 10
echo $b; // 20
echo $c; // 30
What’s the output?

$one = ‘Fred’;
$two = ‘Wilma’;

[$one, $two] = [$two, $one];

echo $one, $two;


Swapping values is now easier

$a = 10;
$b = 20;
[$a, $b] = [$b, $a];

echo $a; // 20
echo $b; // 10
Array destructuring can also be
used with associative arrays

$options = [‘enabled’ => true,


‘comp’ => ‘gzip’];

// Old way
$enabled = $options[‘enabled’];
$comp = $options[‘comp’];

// Array destructuring
[‘enabled’ => $enabled, ‘comp’ => $comp] = $options;
The count() and sizeof()
functions return the number of
elements in the array

family = [‘Fred’, ‘Wilma’, ‘Pebbles’];


$size = count($family); // $size is 3
There are several ways to
loop through arrays
$person = [‘Edison’,
‘Wankel’,
‘Crapper’];

foreach ($person as $name) {


echo “Hello, $name”;
}

Hello, Edison
Hello, Wankel
Hello, Crapper
$creator = [‘Light bulb’ => ‘Edison’,
‘Rotary Engine’ => ‘Wankel’,
‘Toilet’ => ‘Crapper’);

foreach ($creator as $invention => $inventor) {


echo “$inventor created the $invention”;
}

Edison created the Light bulb


Wankel created the Rotary Engine
Crapper created the Toilet
You can sort the elements
of an array with the
various sort functions
$person = [‘Edison’,
‘Wankel’,
‘Crapper’];

sort($person);
// [‘Crapper’, ‘Edison’, ‘Wankel’];
What’s the output?

$family = [‘Fred’, ‘Wilma’];

$family[] = ‘Pebbles’;
$family[] = ‘Dino’;
$family[] = ‘Baby’;

sort($family);
echo $family[2];
$person = [‘Edison’,
‘Wankel’,
‘Crapper’];

rsort($person);
// [‘Wankel’, ‘Edison’, ‘Crapper’];
What’s the output?

$family = [‘Fred’, ‘Wilma’];

$family[] = ‘Pebbles’;
$family[] = ‘Dino’;
$family[] = ‘Baby’;

rsort($family);
echo $family[1];
$creator = [‘Light bulb’ => ‘Edison’,
‘Rotary Engine’ => ‘Wankel’,
‘Toilet’ => ‘Crapper’];

asort($creator);
// [‘Toilet’ => ‘Crapper’,
// ‘Light bulb’ => ‘Edison’,
// ‘Rotary Engine’ => ‘Wankel’];
$creator = [‘Light bulb’ => ‘Edison’,
‘Rotary Engine’ => ‘Wankel’,
‘Toilet’ => ‘Crapper’];

arsort($creator);
// [‘Rotary Engine’ => ‘Wankel’,
// ‘Light bulb’ => ‘Edison’,
// ‘Toilet’ => ‘Crapper’];
There are many other functions
for manipulating arrays:
array_change_key_case(), array_chunk(), array_column(),
array_combine(), array_count_values(), array_diff_assoc(),
array_diff_key(), array_diff_uassoc(), array_diff_ukey(),
array_diff(), array_fill_keys(), array_fill(), array_filter(),
array_flip(), array_intersect_assoc(), array_intersect_key(),
array_intersect_uassoc(), array_intersect_ukey(),
array_intersect(), array_key_exists(), array_keys(),
array_map(), array_merge_recursive(), array_merge(),
array_multisort(), array_pad(), array_pop(), array_product(),
array_push(), array_rand(), array_reduce(),
array_replace_recursive(), array_replace(), array_reverse(),
array_search(), array_shift(), array_slice(), array_splice(),
array_sum(), array_udiff_assoc(), array_udiff_uassoc(), array_udiff(),
array_uintersect_assoc(), array_uintersect_uassoc(),
array_uintersect(), array_unique(), array_unshift(),
array_values(), array_walk_recursive(), array_walk(),
compact(), count(), current(), each(), end(), extract(),
etc.
Flow-Control
Statements
if
if (expression)
statement
else
statement
if ($user_validated)
echo ‘Welcome!’;
else
echo ‘Access Forbidden!’;
if ($user_validated) {
echo ‘Welcome!’;
$greeted = 1;
} else {
echo ‘Access Forbidden!’;
exit;
}
if ($user_validated):
echo ‘Welcome!’;
$greeted = 1;
else:
echo ‘Access Forbidden!’;
exit;
endif;
echo $active ? ‘yes’ : ‘no’;
switch
if ($name == ‘ktatroe’) {
// do something
} else if ($name == ‘dawn’) {
// do something
} else if ($name == ‘petermac’) {
// do something
} else if ($name == ‘bobk’) {
// do something
}
switch($name) {
case ‘ktatroe’:
// do something
break;
case ‘dawn’:
// do something
break;
case ‘petermac’:
// do something
break;
case ‘bobk’:
// do something
break;
}
switch($name):
case ‘ktatroe’:
// do something
break;
case ‘dawn’:
// do something
break;
case ‘petermac’:
// do something
break;
case ‘bobk’:
// do something
break;
endswitch;
while
while (expression) statement
$total = 0;
$i = 1;

while ($i <= 10) {


$total += $i;
$i++;
}
while (expr):
statement;
more statements ;
endwhile;
$total = 0;
$i = 1;

while ($i <= 10):


$total += $i;
$i++;
endwhile;
do
statement
while (expression)
$total = 0;
$i = 1;

do {
$total += $i++;
} while ($i <= 10);
for
for (start; condition; increment) {
statement(s);
}
$total = 0;

for ($i= 1; $i <= 10; $i++) {


$total += $i;
}
for (expr1; expr2; expr3):
statement;
...;
endfor;
$total = 0;

for ($i = 1; $i <= 10; $i++):


$total += $i;
endfor;
foreach
foreach ($array as $current) {
// ...
}
foreach ($array as $current):
// ...
endforeach;
foreach ($array as $key => $value) {
// ...
}
foreach ($array as $key => $value):
// ...
endforeach;
return and
exit
The return
statement returns
from a function
The exit statement
ends execution of the script
as soon as it is reached
(It’s like Java’s System.exit())
The parameter is usually a
string, which is printed before
the process terminates
The function die()
is an alias for this form of
the exit statement
$db = mysql_connect(‘localhost’,
$USERNAME,
$PASSWORD);

if (!$db) {
die(‘Could not connect to database’);
}
$db = mysql_connect(‘localhost’,
$USERNAME,
$PASSWORD)
or die(‘Could not connect to database’);
Including
Code
PHP provides two constructs
to load code and HTML
from another module:
require and include
A common use of include is
to separate page-specific
content from general
site design
<?php include “header.html”; ?>
content
<?php include “footer.html”; ?>
If PHP cannot parse some part of
a file added by include or require,
a warning is printed
You can silence the warning
by prepending the call with the
silence operator @
<?php @include “header.html”; ?>
To define a function,
use the following syntax:

function fn_name([parameter[, ...]]) {


// statement list
}
function strcat($left, $right) {
return $left . $right;
}
Function names are case-insensitive;
that is, you can call the sin() function
as sin(1), SIN(1), SiN(1), and so on
PHP 7 introduces scalar
type declarations

function square(int $num) {


return $num ** 2;
}

echo square(4); // 16
echo square(‘hello’); // error
Variadic functions can be
used since PHP 5.6

function sum(...$num) {
// $num is an array
}

sum(1, 2);
sum(1, 2, 3);
sum(1, 2, 3, 4);
// and so on
What’s the output?

function find(...$num) {
sort($num);
echo $num[1];
}

find(7, 3, 4, 8);
There are four types of
variable scope in PHP:
local, global, static,
and function parameters
Local variable:
A variable declared in a
function is local to that function

function fn1() {
$val = “One”;
}

function fn2() {
echo $val;
}
Global variable:
Variables declared
outside a function
are global
However, by default,
they are not available
inside functions
function updateCounter() {
$counter++; // local
}

$counter = 10; // global


updateCounter();

echo $counter; // 10
function updateCounter() {
global $counter;
$counter++; // global
}

$counter = 10; // global


updateCounter();

echo $counter; // 11
Static variables
retains its value between calls
to a function but is local
function updateCounter() {
static $counter = 0;
$counter++;

echo $counter;
}

updateCounter(); // 1
updateCounter(); // 2
Function parameters
are local, meaning that
they are available
only inside their functions

function greet($name) {
echo “Hello, $name”;
}

greet(‘Janet’); // Hello, Janet


A function can have
one or more default values

function makecoffee($type=‘cappuccino’) {
return “Making a cup of $type.”;
}

echo makecoffee();
echo makecoffee(‘espresso’);

Making a cup of cappuccino.


Making a cup of espresso.
To have an argument passed by
reference, prepend the
parameter with a &

function increment(&$num) {
$num += 10;
}
Since PHP 7, return types
can be declared

function voidFunction(): float {


return ‘Hello’; // error
}
Since PHP 7.1, functions
can be declared void

function voidFunction(): void {


return ‘Hello’; // error
}
We can call the function
whose name is the value
held by variable
(called variable functions)
switch ($which) {
case ‘first’:
first();
break;
case ‘second’:
second();
break;
case ‘third’:
third();
break;
}
// if $which is ‘first’,
// the function first()
// is called, etc...
$which();
What’s the output?

function one() { $foo = ‘one’;


echo 1; $$foo = ‘two’;
}
$$foo();
function two() {
echo 2;
}
You can create an anonymous function
using the normal function definition syntax,
but assign it to a variable or pass it

usort($array, function($a, $b) {


return strlen($a) - strlen($b);
});
bye
.

You might also like