Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays.

Similar presentations


Presentation on theme: "Arrays."— Presentation transcript:

1 Arrays

2 We can identify an array by position
(called indexed arrays) $person[0] = ‘Edison’; $person[1] = ‘Wankel’; $person[2] = ‘Crapper’;

3 (called associative arrays)
... or by name (a string) (called associative arrays) $creator[‘Light bulb’] = ‘Edison’; $creator[‘Rotary Engine’] = ‘Wankel’; $creator[‘Toilet’] = ‘Crapper’;

4 What’s the output? $foo = ‘bar’; $arr[‘bar’] = ‘good’;
$arr[‘$foo’] = ‘morning’; echo $arr[‘bar’]; echo $arr[“$foo”];

5 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’);

6 shorter way to create arrays
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’];

7 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];

8 What’s the output? $letters = range(‘z’, ‘a’); echo $letters[4];

9 The print_r() intelligently displays what is passed to it

10 $a = [‘name’ => ‘Fred’,
‘age’ => 35, ‘wife’ => ‘Wilma’]; echo $a; print_r($a); Array ( [name] => Fred [age] => 35 [wife] => Wilma)

11 We can also use var_dump()

12 $a = [‘name’ => ‘Fred’,
‘age’ => 35, ‘wife’ => ‘Wilma’]; var_dump($a); array(3) { [“name”]=> string(4) “Fred” [“age”]=> int(35) [“wife”]=> string(5) “Wilma” }

13 into the end of an existing indexed array, use the [] syntax
To insert more values into the end of an existing indexed array, use the [] syntax $family = [‘Fred’, ‘Wilma’]; $family[] = ‘Pebbles’; // [‘Fred’, ‘Wilma’, ‘Pebbles’]

14 What’s the output? $family = [‘Fred’, ‘Wilma’]; $family[] = ‘Pebbles’;
$family[] = ‘Dino’; $family[] = ‘Baby’; echo $family[4];

15 PHP 7.1 offers array destructuring feature
[$a, $b, $c] = $arr; echo $a; // 10 echo $b; // 20 echo $c; // 30

16 What’s the output? $one = ‘Fred’; $two = ‘Wilma’;
[$one, $two] = [$two, $one]; echo $one, $two;

17 Swapping values is now easier
$b = 20; [$a, $b] = [$b, $a]; echo $a; // 20 echo $b; // 10

18 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;

19 The count() and sizeof() functions return the number of
elements in the array family = [‘Fred’, ‘Wilma’, ‘Pebbles’]; $size = count($family); // $size is 3

20 There are several ways to
loop through arrays

21 $person = [‘Edison’, ‘Wankel’, ‘Crapper’]; foreach($person as $name) { echo “Hello, {$name}\n”; } Hello, Edison Hello, Wankel Hello, Crapper

22 $creator = [‘Light bulb’ => ‘Edison’,
‘Rotary Engine’ => ‘Wankel’, ‘Toilet’ => ‘Crapper’); foreach($creator as $invention => $inventor) { echo “{$inventor} created the {$invention}\n”; } Edison created the Light bulb Wankel created the Rotary Engine Crapper created the Toilet

23 You can sort the elements of an array with the various sort functions

24 $person = [‘Edison’, ‘Wankel’, ‘Crapper’]; sort($person); // [‘Crapper’, ‘Edison’, ‘Wankel’];

25 What’s the output? $family = [‘Fred’, ‘Wilma’]; $family[] = ‘Pebbles’;
$family[] = ‘Dino’; $family[] = ‘Baby’; sort($family); echo $family[2];

26 $person = [‘Edison’, ‘Wankel’, ‘Crapper’]; rsort($person); // [‘Wankel’, ‘Edison’, ‘Crapper’];

27 What’s the output? $family = [‘Fred’, ‘Wilma’]; $family[] = ‘Pebbles’;
$family[] = ‘Dino’; $family[] = ‘Baby’; rsort($family); echo $family[1];

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

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

30 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.

31 Flow-Control Statements

32 if

33 if (expression) statement else

34 if ($user_validated) echo ‘Welcome!’; else echo ‘Access Forbidden!’;

35 if ($user_validated) {
echo ‘Welcome!’; $greeted = 1; } else { echo ‘Access Forbidden!’; exit; }

36 if ($user_validated):
echo ‘Welcome!’; $greeted = 1; else: echo ‘Access Forbidden!’; exit; endif;

37 echo $active ? ‘yes’ : ‘no’;

38 switch

39 if ($name == ‘ktatroe’) {
// do something } else if ($name == ‘dawn’) { } else if ($name == ‘petermac’) { } else if ($name == ‘bobk’) { }

40 switch($name) { case ‘ktatroe’: // do something break; case ‘dawn’: case ‘petermac’: case ‘bobk’: }

41 switch($name): case ‘ktatroe’: // do something break; case ‘dawn’: case ‘petermac’: case ‘bobk’: endswitch;

42 while

43 while (expression) statement

44 $total = 0; $i = 1; while ($i <= 10) { $total += $i; $i++; }

45 while (expr): statement; more statements ; endwhile;

46 $total = 0; $i = 1; while ($i <= 10): $total += $i; $i++; endwhile;

47 do statement while (expression)

48 $total = 0; $i = 1; do { $total += $i++; } while ($i <= 10);

49 for

50 for (start; condition; increment) {
statement(s); }

51 $total = 0; for ($i= 1; $i <= 10; $i++) { $total += $i; }

52 for (expr1; expr2; expr3):
statement; ...; endfor;

53 $total = 0; for ($i = 1; $i <= 10; $i++): $total += $i; endfor;

54 foreach

55 foreach ($array as $current) {
// ... }

56 foreach ($array as $current):
// ... endforeach;

57 foreach ($array as $key => $value) {
// ... }

58 foreach ($array as $key => $value):
// ... endforeach;

59 return and exit

60 The return statement returns from a function

61 ends execution of the script as soon as it is reached
The exit statement ends execution of the script as soon as it is reached (It’s like Java’s System.exit())

62 It is usually a string, which is printed before the process terminates

63 is an alias for this form of
The function die() is an alias for this form of the exit statement

64 $db = mysql_connect(‘localhost’,
$USERNAME, $PASSWORD); if (!$db) { die(‘Could not connect to database’); }

65 $db = mysql_connect(‘localhost’,
$USERNAME, $PASSWORD) or die(‘Could not connect to database’);

66 Including Code

67 PHP provides two constructs
to load code and HTML from another module: require and include

68 A common use of include is to separate page-specific
content from general site design

69 <?php include “header.html”; ?>
content <?php include “footer.html”; ?>

70 If PHP cannot parse some part of a file added by include or require,
a warning is printed

71 You can silence the warning by prepending the call with the
silence

72 <?php @include “header.html”; ?>

73 Functions

74 use the following syntax:
To define a function, use the following syntax: function fn_name([parameter[, ...]]) { // statement list }

75 function strcat($left, $right) {
return $left . $right; }

76 Function names are case-insensitive;
that is, you can call the sin() function as sin(1), SIN(1), SiN(1), and so on

77 PHP 7 introduces scalar type declarations
function square(int $num) { return $num ** 2; } echo square(4); // 16 echo square(‘hello’); // error

78 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

79 What’s the output? function find(...$num) { sort($num); echo $num[1];
} find(7, 3, 4, 8);

80 and function parameters
There are four types of variable scope in PHP: local, global, static, and function parameters

81 Local variable: A variable declared in a
function is local to that function function fn1() { $val = “One”; } function fn2() { echo $val;

82 Global variable: Variables declared outside a function are global

83 However, by default, they are not available inside functions

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

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

86 Static variables retains its value between calls
to a function but is local

87 function updateCounter() {
static $counter = 0; $counter++; echo $counter; } updateCounter(); // 1 updateCounter(); // 2

88 only inside their functions
Function parameters are local, meaning that they are available only inside their functions function greet($name) { echo “Hello, $name”; } greet(‘Janet’); // Hello, Janet

89 one or more default values
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.

90 use the return statement
To return a value from, use the return statement function returnOne() { return 42; }

91 Since PHP 7, return types can be declared
function voidFunction(): float { return ‘Hello’; // error }

92 Since PHP 7.1, functions can be declared void
function voidFunction(): void { return ‘Hello’; // error }

93 We can call the function whose name is the value held by variable
(called variable functions)

94 switch ($which) { case ‘first’: first(); break; case ‘second’: second(); case ‘third’: third(); }

95 // if $which is ‘first’, // the function first() // is called, etc... $which();

96 What’s the output? function one() { echo 1; } function two() { echo 2;
$foo = ‘one’; $$foo = ‘two’; $$foo();

97 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); });

98 bye.


Download ppt "Arrays."

Similar presentations


Ads by Google