introduction to php – part 2 sudeshna dey. arrays a series of homogeneous elements elements have...

30
Introduction to PHP – Part 2 Sudeshna Dey

Upload: loren-merritt

Post on 03-Jan-2016

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Introduction to PHP – Part 2

Sudeshna Dey

Page 2: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Arrays

• A series of homogeneous elements• Elements have values in form of stored data• Has a key associated with every element– Values get associated to keys– Arrays specified as key-value pairs

• Effectively an ordered map

Page 3: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Arrays (cont’d)

• Initialization can be done in different ways• Ex: array( key => value, key2 => value2, key3

=> value3, ... )– Comma after the last element is optional and may

not be used

• The key is usually an Integer or a String• The value can be of any data type

Page 4: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Arrays (cont’d)// On earlier versions<?php$array = array(“key1" => “value1",“key2" => “value2",);

// PHP 5.4 onwards$array = [“key1" => “value1",“key2" => “value2",];?>

Page 5: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Arrays (cont’d)• If multiple elements in the array declaration use the same key, only the

last one will be used as all others are overwritten• Input

– <?php$array = array(1 => “x",1.7 => “y","1" => “z");?>

• Output– array(1) { [1]=> string(1) “z" }

Page 6: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Arrays (cont’d)

• Useful in passing messages across webpages– <?php

$error_desc [ERROR] = “Fatal error, cannot proceed further";$error_desc [WARNING] = “Warning message, please double-check source";$error_desc [INFO] = “Great programming!";?>

• Used to pass around session variables using named keys

• If no index is specified, then the default indexing starts at 0 (integer) and then counts upwards as one keeps adding elements to the array

Page 7: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Arrays (cont’d)$first = array();$first[‘size'] = ‘big';$first[‘shape'] = ‘cubic';$first[‘density'] = ‘high';$first[‘type'] = ‘compound';$first[] = 100; // $first[0]=100;

$second = array();$second[] = ‘x';$second[] = ‘y';$second[] = ‘z';

// Result of the above:// $first = array('size' => 'big', 'shape' => 'cubic', 'density' => 'high ', 'type' => 'compound', '0' => 100)// $second = array(0 => 'x‘, 1 => 'y', 2 => 'z')

Page 8: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)<?php// Create a simple array.$array = array(1, 2, 3, 4, 5);print_r($array);

// Now delete every item, but leave the array itself intact:foreach ($array as $i => $value) {unset($array[$i]);}print_r($array);

// Append an item (note that the new key is 5, instead of 0).$array[] = 6;print_r($array);

// Re-index:$array = array_values($array);$array[] = 7;print_r($array);?>

Page 9: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• By default, arrays are 0-index based• But, one can set 1-index based arrays

<?php$firstquarter = array(1 => 'January', 'February', 'March');print_r($firstquarter);?>

Output array ( [1] => 'January' [2] => 'February' [3] => 'March' )

Page 10: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• Arrays can be sorted with inbuilt commands<?php

sort($array); // sorts the arrayprint_r($array);?>

Page 11: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• Arrays can have any content inside them

– Hence, arrays can contain arrays– This leads to creation of multidimensional and recursive arrays

<?php$fruits = array ( "fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple"),"numbers" => array ( 1, 2, 3, 4, 5, 6), "holes" => array ( "first", 5 => "second", "third"));

// Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second"echo $fruits["fruits"]["a"]; // prints "orange"unset($fruits["holes"][0]); // remove "first"

// Create a new multi-dimensional array$juices["apple"]["green"] = "good"; ?>

Page 12: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• Array assignment involves copying one array into the other• Involves value-copying

– <?php$arr1 = array(2, 3);$arr2 = $arr1;$arr2[] = 4; // $arr2 is changed,// $arr1 is still array(2, 3)

$arr3 = &$arr1;$arr3[] = 4; // now $arr1 and $arr3 are the same?>

Page 13: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_diff() function compares array values two or more arrays

– Returns an array with the keys and values from the first array, only if the value is not present in any of the other arrays

– Only the value is used for the comparison, not the key– <?php

$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");$a2=array(3=>"Horse",4=>"Dog",5=>"Fish");print_r(array_diff($a1,$a2));?>

– Output: Array ( [0] => Cat )

• General syntax: array_diff(array1,array2,array3...)

Page 14: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_diff_assoc() function compares two or more arrays

– Returns an array with the keys and values from the first array, only if they are not present in any of the other arrays

– Uses both the keys and the values for comparison– <?php

$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");$a2=array(0=>"Rat",1=>"Horse",2=>"Dog");$a3=array(0=>"Horse",1=>"Dog",2=>"Cat");print_r(array_diff_assoc($a1,$a2,$a3));?>

– Output: Array ( [0] => Cat [2] => Horse )

• General syntax: array_diff_assoc(array1,array2,array3...)

Page 15: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_combine() function creates an array by combining two other

arrays– The first array is the keys– The second array is the values

• General syntax: array_combine(array1,array2)• <?php

$a1=array("a","b","c","d");$a2=array("Cat","Dog","Horse","Cow");print_r(array_combine($a1,$a2));?>

• Output: Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow )

Page 16: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_filter() function passes each value in the array to a user-made function

– The user-made function returns either true or false– The array_filter() returns an array only with the values that returned true– <?php

function myfunction($v){if ($v==="Horse"){return true;}return false;}$a=array(0=>"Dog",1=>"Cat",2=>"Horse");print_r(array_filter($a,"myfunction"));?>

– Output: Array ( [2] => Horse )

Page 17: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• The array_intersect() function compares two or more arrays– Returns an array with the keys and values from the first

array, only if the value is present in all of the other arrays– <?php

$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");$a2=array(3=>"Horse",4=>"Dog",5=>"Fish");print_r(array_intersect($a1,$a2));?>

– Output: Array ( [1] => Dog [2] => Horse )

Page 18: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_key_exists() function checks an array for a specified key

– Returns true if the key exists– Returns false if the key does not exist– <?php

$a=array("a"=>"Dog","b"=>"Cat");if (array_key_exists("a",$a)){echo "Key exists!";}else{echo "Key does not exist!";}?>

– Output: Key exists!

Page 19: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• The array_merge() function merges one or more arrays into one array– <?php

$a1=array("a"=>"Horse","b"=>"Dog");$a2=array("c"=>"Cow","b"=>"Cat");print_r(array_merge($a1,$a2));?>

– Output: Array ( [a] => Horse [b] => Cat [c] => Cow )

• Can use array_merge() with only one parameter

Page 20: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_merge_recursive() function merges one ore more arrays into one array• The difference between this function and the array_merge() function is when two

or more array elements have the same key, instead of override the keys, the array_merge_recursivse() function makes the value as an array

• Sample code:– <?php

$a1=array("a"=>"Horse","b"=>"Dog");$a2=array("c"=>"Cow","b"=>"Cat");print_r(array_merge_recursive($a1,$a2));?>

– Output: Array ([a] => Horse[b] => Array ( [0] => Dog [1] => Cat )[c] => Cow)

Page 21: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• The array_pop() function deletes the last element of an array– <?php

$a=array("Dog","Cat","Horse");array_pop($a);print_r($a);?>

– Output: Array ( [0] => Dog [1] => Cat )– General syntax: array_pop(array)

Page 22: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• The array_reverse() function returns an array in the reverse order– <?php

$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");print_r(array_reverse($a));?>

– Output: Array ( [c] => Horse [b] => Cat [a] => Dog )

Page 23: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_shift() function removes the first element from an array

– Returns the value of the removed element– <?php

$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");echo array_shift($a);print_r ($a);?>

– Output:• Dog• Array ( [b] => Cat [c] => Horse )

– If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1

– <?php$a=array(0=>"Dog",1=>"Cat",2=>"Horse");echo array_shift($a);print_r ($a);?>

– Output:• Dog• Array ( [0] => Cat [1] => Horse )

Page 24: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The array_walk() function runs each array element in a user-made

function– The array's keys and values are parameters in the function– Returns True or False– <?php

function myfunction($value,$key){echo "The key $key has the value $value<br />";}$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");array_walk($a,"myfunction");?>

– Output:• The key a has the value Cat

The key b has the value DogThe key c has the value Horse

Page 25: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The asort() function sorts an array by the values

– Values keep their original keys– Returns TRUE on success, or FALSE on failure– <?php

$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

asort($my_array);print_r($my_array);?>

– Output: Array([b] => Cat[a] => Dog[c] => Horse)

Page 26: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The arsort() function sorts an array by the values in reverse order

– Values keep their original keys.– Returns TRUE on success, or FALSE on failure– <?php

$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

arsort($my_array);print_r($my_array);?>

– Output: Array([c] => Horse[a] => Dog[b] => Cat)

Page 27: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• The array_values() function returns an array containing all the values of an array– <?php

$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");print_r(array_values($a));?>

– Output: Array ( [0] => Cat [1] => Dog [2] => Horse )

Page 28: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• The array_sum() function returns the sum of all the values in the array– <?php

$a=array(0=>"5",1=>"15",2=>"25");echo array_sum($a);?>

– Output: 45

Page 29: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)• The explode() function breaks a string into an array

– General syntax: explode(separator,string,limit)– <?php

$str = "Hello world. It's a beautiful day.";print_r (explode(" ",$str));?>

– Output: Array([0] => Hello[1] => world.[2] => It's[3] => a[4] => beautiful[5] => day.)

Page 30: Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with

Array (cont’d)

• The implode() function returns a string from the elements of an array– General syntax: implode(separator,array)

• The separator parameter is optional these days, but recommended to use for backward compatibility

– <?php$arr = array('Hello','World!','Beautiful','Day!');echo implode(" ",$arr);?>

– Output: Hello World! Beautiful Day!