340 likes | 481 Views
Working with Arrays. PHP Session # 3. Slides by npguy. Array. An array is made up of elements. Each element has a key and a value. $music = array (“flute”, “guitar”, “jazz”); echo $music[ 0 ]; here, key is 0 , and value is “flute”. Note.
E N D
Working with Arrays PHP Session # 3 Slides by npguy
Array • An array is made up of elements. Each element has a key and a value. $music = array(“flute”, “guitar”, “jazz”); echo $music[0]; here, key is 0, and value is “flute”
Note • Unlike C/C++ or Java. An array size in PHP can be grown or allocate dynamically. Like $x[100]=30; $y[3000]=23; $y[3001]=34; A PHP Array can hold different data types$test[0]=“kathmandu”; $test[1]=449333494; $test[2]=76.34;
Associated Array $color = array(“corn”=>”yellow”, “beet”=>”red”, “carrot”=>”orange”, “pepper”=>”green”, “orange”=>”orange”); echo $color[“corn”];
Array value A value can be of any PHP type. Like, $item = array ( “id” => array(10 => “sarose”, 20 => “rose”, 30 => “test”, “007” => “bond”) ); echo $item[“id”][20]; echo $item[“id”][“007”];
Array values $t = array(5 => 43, 32, 56, "b" => 12); // This array is the same as ... $t = array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
Adding new elements • The empty brackets [ ] add an element // Create $city with three elements $city = array(‘Ktm', ‘Pkr', ‘Brt'); // Add an element to the end of $city$dinner[ ] = ‘Palpa'; $dinner[ ]= ‘Btl’; print_r($dinner); // next slide tells about print_r
print_r(...); • Prints human-readable information about a variable $a = array ('a' => 'apple', 'b' => 'banana', 'c' =>’cat’); print_r ($a); // Output Array ( [a] => apple [b] => banana [c] => cat ) It is useful for debugging purposes.
Removing element // Create $city with three elements $city = array(‘Ktm', ‘Pkr', ‘Brt'); // This removes 1st element of $city. unset($ city[1]); print_r($city); // removes whole $city.unset($city); print_r($city);
Looping Through Arrays $letters[0] = 'A'; $letters[1] = 'B'; $letters[3] = 'D'; $letters[2] = 'C'; foreach ($letters as $letter) { print $letter; }
Getting key and value $country = array(‘np' => ‘Nepal', ‘in' => ‘India', ‘ca' => ‘Canada', ‘uk' => ‘United Kingdom’); foreach ($country as $key=>$value) { print “ $key ------ $value <br> \n"; }
foreach dimensional arrays $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { print "$v2\n"; } }
Finding the Size of an Array • `count` function returns the total number of element. $city = array (34,23,45,34); $total = count($city); $total = sizeof($city); //same as count
Checking for an element • To check for an element with a certain key, use array_key_exists( ) $country = array(‘np' => ‘Nepal', ‘in' => ‘India', ‘ca' => ‘Canada', ‘uk' => ‘United Kingdom’); if (array_key_exists(‘uk',$country)) { print "Yes, we accept uk shipping."; }
Checking for a value $country = array(‘np' => ‘Nepal', ‘in' => ‘India', ‘ca' => ‘Canada', ‘uk' => ‘United Kingdom’); If ( in_array(‘Canada’, $country) ) { print “Cannot shipping not accepted."; }
Sorting numeric arrays • The sort( ) function sorts an array by its element values. It should only be used on numeric arrays, because it resets the keys of the array when it sorts $city = array(‘wd’,’nd’,‘ktm’,’pkr’,’brt’); sort($city); foreach ($city as $key => $value) { print " \$meal: $key $value\n"; }
Sorting an associative array • use asort( ). This keeps keys together with their values. $country = array(‘np' => ‘Nepal', ‘in' => ‘India', ‘ca' => ‘Canada', ‘uk' => ‘United Kingdom’); foreach ($country as $key => $value) print " $key $value\n"; asort($country); foreach ($country as $key => $value) print " $key $value\n";
sort arrays by key $country = array(‘np' => ‘Nepal', ‘in' => ‘India', ‘ca' => ‘Canada', ‘uk' => ‘United Kingdom’); ksort($country); foreach ($country as $key => $value) print " $key $value\n";
Reverse sorting • The reverse-sorting functions are named rsort( ), arsort( ), and krsort( )
array_diff • Computes the difference of arrays $a1 = array ("a" => "green", "red", "blue", "red"); $a2 = array ("b" => "green", "yellow", "red"); $result = array_diff ($array1, $array2); print_r($result); // This makes $result have array ("blue");
array_merge • Merge two or more arrays $array1 = array ("color" => "red", 2, 4); $array2 = array ("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge ($array1, $array2); print_r($result);
Note on Array_merge • If keys is exist in next array it will be overwritten.
array_pop $stack = array ("orange", "banana", "apple", "raspberry"); $fruit = array_pop ($stack); print_r($stack); OutputArray ( [0] => orange [1] => banana [2] => apple )
array_push • Push one or more elements onto the end of array $stack = array ("orange", "banana"); array_push ($stack, "apple", "raspberry"); print_r($stack);
array_slice • Extract a slice of the array $input = array ("a", "b", "c", "d", "e"); $output = array_slice ($input, 2); // returns "c", "d", and "e" $output = array_slice ($input, 2, -1); // returns "c", "d" $output = array_slice ($input, -2, 1); // returns "d"
array_sum $a = array(2, 4, 6, 8); $sum = array_sum($a);echo “ Total suim : “.$sum; $b = array("a"=>1.2,"b"=>2.3,"c"=>3.4); $tot = array_sum($b) echo “Total sum: $tot \n";
array_unique • Removes duplicate values from an array $input = array ("a" => "green", "red", "b" => "green", "blue", "red"); $result = array_unique ($input); print_r($result);
array_intersect • Computes the intersection of arrays $array1 = array ("a" => "green", "red", "blue"); $array2 = array ("b" => "green", "yellow", "red"); $result = array_intersect ($array1, $array2); print_r($result);
range // array(0,1,2,3,4,5,6,7,8,9,10,11,12) foreach(range(0, 12) as $number) { echo $number; } // array('a','b','c','d','e','f','g','h','i'); foreach(range('a', 'i') as $letter) { echo $letter; }
list • Assign variables as if they were an array . $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo $drink, $color, $power;
Multidimensional Arrays $items = array( 'os' => array('win32','bsd','linux') , 'editor' => array('vi', 'scite','notepad'), 'game' => array('doom','quake','tr3') ); echo $items['os'][1]; // prints -- bsd
with key => value $flavors = array( 'Japanese' => array('hot' => 'wasabi', 'salty' => 'soy sauce'), 'Chinese' => array('hot' => 'mustard', 'salty' => 'prickly ash') ); echo $flavors[‘Chinese‘][‘salty’]; //prints ??
Superglobals array Will be discussed in session # 4
Read php manual • PHP has dozen of array related function. • Its beyond the scope of this slide • Open php manual and see Array function. • Start practice now!