1 / 34

Working with Arrays

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.

tucker
Télécharger la présentation

Working with Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Working with Arrays PHP Session # 3 Slides by npguy

  2. 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”

  3. 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;

  4. Associated Array $color = array(“corn”=>”yellow”, “beet”=>”red”, “carrot”=>”orange”, “pepper”=>”green”, “orange”=>”orange”); echo $color[“corn”];

  5. 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”];

  6. 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);

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

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

  9. 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);

  10. Looping Through Arrays $letters[0] = 'A'; $letters[1] = 'B'; $letters[3] = 'D'; $letters[2] = 'C'; foreach ($letters as $letter) { print $letter; }

  11. 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"; }

  12. 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"; } }

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

  14. 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."; }

  15. 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."; }

  16. 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"; }

  17. 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";

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

  19. Reverse sorting • The reverse-sorting functions are named rsort( ), arsort( ), and krsort( )

  20. 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");

  21. 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);

  22. Note on Array_merge • If keys is exist in next array it will be overwritten.

  23. array_pop $stack = array ("orange", "banana", "apple", "raspberry"); $fruit = array_pop ($stack); print_r($stack); OutputArray ( [0] => orange [1] => banana [2] => apple )

  24. array_push • Push one or more elements onto the end of array $stack = array ("orange", "banana"); array_push ($stack, "apple", "raspberry"); print_r($stack);

  25. 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"

  26. 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";

  27. array_unique • Removes duplicate values from an array $input = array ("a" => "green", "red", "b" => "green", "blue", "red"); $result = array_unique ($input); print_r($result);

  28. 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);

  29. 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; }

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

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

  32. with key => value $flavors = array( 'Japanese' => array('hot' => 'wasabi', 'salty' => 'soy sauce'), 'Chinese' => array('hot' => 'mustard', 'salty' => 'prickly ash') ); echo $flavors[‘Chinese‘][‘salty’]; //prints ??

  33. Superglobals array Will be discussed in session # 4

  34. 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!

More Related