Professional Documents
Culture Documents
array
by position
(called indexed arrays)
$person[0] = ‘Edison’;
$person[1] = ‘Wankel’;
$person[2] = ‘Crapper’;
... or by name (a string)
(called associative arrays)
$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
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[] = ‘Pebbles’;
// [‘Fred’, ‘Wilma’, ‘Pebbles’]
What’s the output?
$family[] = ‘Pebbles’;
$family[] = ‘Dino’;
$family[] = ‘Baby’;
echo $family[4];
PHP 7.1 offers array
destructuring feature
echo $a; // 10
echo $b; // 20
echo $c; // 30
What’s the output?
$one = ‘Fred’;
$two = ‘Wilma’;
$a = 10;
$b = 20;
[$a, $b] = [$b, $a];
echo $a; // 20
echo $b; // 10
Array destructuring can also be
used with associative arrays
// 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
Hello, Edison
Hello, Wankel
Hello, Crapper
$creator = [‘Light bulb’ => ‘Edison’,
‘Rotary Engine’ => ‘Wankel’,
‘Toilet’ => ‘Crapper’);
sort($person);
// [‘Crapper’, ‘Edison’, ‘Wankel’];
What’s the output?
$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[] = ‘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;
do {
$total += $i++;
} while ($i <= 10);
for
for (start; condition; increment) {
statement(s);
}
$total = 0;
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:
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
}
echo $counter; // 10
function updateCounter() {
global $counter;
$counter++; // global
}
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”;
}
function makecoffee($type=‘cappuccino’) {
return “Making a cup of $type.”;
}
echo makecoffee();
echo makecoffee(‘espresso’);
function increment(&$num) {
$num += 10;
}
Since PHP 7, return types
can be declared