270 likes | 421 Views
Arrays. C SCI 116. Variables. $animals = " ostrich" ; $ animals = " anteater"; $animals = " orangutan"; $animals = " cheetah"; $animals = " hyena"; . What does $animals contain?. Arrays. “ostrich” “anteater” “orangutan” “cheetah” “hyena” . $animals[] .
E N D
Arrays C SCI 116
Variables $animals = "ostrich"; $animals = "anteater"; $animals = "orangutan"; $animals = "cheetah"; $animals = "hyena"; What does $animals contain?
Arrays “ostrich” “anteater” “orangutan” “cheetah” “hyena” $animals[] $animals[] = "ostrich"; $animals[] = "anteater"; $animals[] = "orangutan"; $animals[] = "cheetah"; $animals[] = "hyena"; An array contains a set of data represented by a single variable name A “list” of values
Declaring and Initializing Indexed Arrays • An element refers to a piece of data stored in an array • An index is an element’s numeric position within the array • By default, indexes start with zero (0) • An array element is referenced by enclosing its index in brackets after the array name: print $animals[0];
Predefined Arrays • PHP has a number of built-in arrays • Example: $_SERVER • Also called autoglobalarrays • $_SERVER • $_POST • $_GET • $_COOKIE • $_SESSION
Printing Arrays <?php print_r($_SERVER); ?> Much prettier <?php print "<pre>"; print_r($_SERVER); print "</pre>"; ?> Use print_rto quickly display array contents Not useful for user output
Creating an Array: Revisited • $animals = array("ostrich", "anteater", "orangutan", "cheetah", "hyena"); – OR – • $animals[] = "ostrich"; • $animals[] = "anteater"; • $animals[] = "orangutan"; • $animals[] = "cheetah"; • $animals[] = "hyena"; $array_name = array(values);
Looping through an Array ostrich anteater orangutan cheetah hyena for ($i=0; $i<sizeof($animals); $i++) { print $animals[$i] . "<br>"; //print "{$animals[$i]}<br>"; }
foreachLoops • Used to loop through the elements in an array • Does not require a counter • Syntax: foreach ($array_name as $variable_name) { statements; }
foreach Example foreach($animals as $animal) { print "$animal<br>"; }
Practice Create an array called $names that contains the names of 5 of your classmates Print the array using print_r Print the first name in the array Print the last name in the array Print the array using a for loop Print the array using a for-each loop
Associative Arrays • With associative arrays, you specify an element’s key by using the array operator (=>) • Syntax : $array_name = array(key=>value, ...); PHP Programming with MySQL
Associative Arrays $capitals = array("Texas" => "Austen", "Oregon" => "Salem", "Ohio" => "Columbus", "New York" => "Albany"); print "The capital of Texas is " . $capitals['Texas']; print "The capital of Texas is {$capitals['Texas']}"; The capital of Texas is Austen PHP Programming with MySQL
Associative Arrays $capitals = array("Texas" => "Austen", "Oregon" => "Salem", "Ohio" => "Columbus", "New York" => "Albany"); foreach ($capitals as $state => $capital) { print "The capital of $state is $capital.<br>"; } The capital of Texas is Austen. The capital of Oregon is Salem. The capital of Ohio is Columbus. The capital of New York is Albany. PHP Programming with MySQL
count() or sizeof() • Use count()or sizeof() to find the total number of elements in an array $capitals = array("Texas" => "Austen", "Oregon" => "Portland", "Ohio" => "Columbus", "New York" => "Albany"); echo "There are " . count($capitals) . " capitals."; There are 4 capitals.
Converting Strings to Arrays • Use the explode() function to convert a string to an array • $array = explode(separators, string); • If the string does not contain the specified separators, the entire string is assigned to the first element of the array ostrich anteater orangutan cheetah hyena $animals = "ostrich,anteater, orangutan,cheetah,hyena"; $animal_array= explode(",", $animals); foreach ($animal_array as $animal) echo "$animal<br>";
Converting Arrays to Strings • Use the implode() function to convert an array to a string • $variable = implode(separators, array); • If the string does not contain the specified separators, the entire string is assigned to the first element of the array $presArray= array("George W. Bush", "William Clinton", "George H.W. Bush", "Ronald Reagan", "Jimmy Carter"); $presidents = implode(", ", $presArray); echo $presidents;
Removing Duplicates • The array_unique() function removes duplicate elements from an array • Pass the array name PHP Programming with MySQL
array_unique() $topGolfers= array( "Tiger Woods", "Tiger Woods", "Vijay Singh”, "Vijay Singh", "Ernie Els", "Phil Mickelson", "Retief Goosen", "Retief Goosen", "Padraig Harrington", "David Toms", "Sergio Garcia", "Adam Scott", "Stewart Cink"); echo "The world's top golfers are:<p>”; $topGolfers= array_unique($topGolfers); foreach($topGolfersas $golfer) { echo "$golfer<br>"; } echo "</p>"; PHP Programming with MySQL
Determining if a Value Exists • in_array()returns Boolean TRUE if a given value exists in an array • array_search()determines whether a given value exists in an array and • Returns the index or key of the first matching element if the value exists, or • Returns false if the value does not exist if (in_array(“Neurology”, $hospitalDepts)) { echo "The hospital has a Neurology department."; } PHP Programming with MySQL
Determining if a Key Exists • array_key_existsdetermines whether a given index or key exists • array_key_exists($search_key, $array) $GamePieces["Dancer"] = "Daryl"; $GamePieces["Fat Man"] = "Dennis"; $GamePieces["Assassin"] = "Jennifer"; if (array_key_exists("Fat Man", $GamePieces)) { echo "{$GamePieces["Fat Man"]} is 'Fat Man'."; } PHP Programming with MySQL
Sorting Arrays • The most commonly used array sorting functions are: • sort() and rsort() for indexed arrays • ksort() and krsort() for associative arrays PHP Programming with MySQL
sort() rsort() PHP Programming with MySQL
Practice Display your $names array in alphabetical order Display your $names array in reverse alphabetical order
Combining Arrays • To merge two or more arrays use the array_merge() function • Syntax: new_array= array_merge($array1, $array2, $array3, ...); PHP Programming with MySQL
Combining Arrays (continued) $mammals = array("cat", "dog", "bear"); $reptiles = array("snake", "lizard"); $birds = array("emu", "parakeet", "canary"); $animals = array_merge($mammals, $reptiles, $birds); print_r($animals); Array ( [0] => cat [1] => dog [2] => bear [3] => snake [4] => lizard [5] => emu [6] => parakeet [7] => canary ) PHP Programming with MySQL
Practice Create a second array called $family_names. Add at least three names to the array. Merge $names and $family_namesinto an array called $all_names. Remove any duplicates from $all_names. Print $all_names.