all the conditional actions we've looked at so far involve something being either true or false. there is often a situation where you have to test for multiple possibilities, though. that can be achieved using the methods we've already looked at but it is very messy.
$fruit = "banana";
if($fruit == "apple") {
print_r("you picked an apple.");
else{
if ($fruit == "orange") {
print_r("you picked an orange.");
else{
if ($fruit == "tomato") {
print_r("you picked a tomato.");
else{
if ($fruit == "banana") {
print_r("you picked a banana.");
else{
if ($fruit == "peach") {
print_r("you picked a peach.");
else{
print_r("i'm not sure what you picked.");
}
}
}
}
}
returns you picked a banana.. this is completely valid php code and will certainly work without any errors but there is a much friendlier way to do the same thing using switch.
$fruit = "banana";
switch($fruit) {
case "apple":
print_r("you picked an apple.");
break;
case "orange":
print_r("you picked an orange.");
break;
case "tomato":
print_r("you picked a tomato.");
break;
case "banana":
print_r("you picked a banana.");
break;
case "peach":
print_r("you picked a peach.");
break;
default:
print_r("i'm not sure what you picked.");
break;
}
this code works the same way but avoids all the headaches of nested if statements. instead of multiple levels, it just checks for one possibility then, if it's a match, runs everything until it reaches break or the end of the switch block. if it gets to the end of the list without a match, it runs whatever's in the default section, if there is one. default is optional in switch.
the most common way to gather a collection of information together in php is using an array. we have already seen arrays in some examples when we talked about types of variables but now we can look at what an array is in greater depth.
a variable (or constant, though those are less common in php) is a single piece of information. it can be a very large piece of information like an entire file or the text of a book. but it is one continuous block of data. an array is a collection of any number of those blocks of data in a particular order. the fact that it is in a specific order is what makes it more useful than just having independent blocks of data as their own variables.
the simplest form of array is self-numbering. note that the numbers always begin from 0 rather than 1 so the fourth piece of information in an array is 3 and the tenth is 9. this is common but not universal across languages.
$myFirstArray = [10, 8, 3, 7, 9, 2, 4];
defining an array is no different from creating a variable. it uses the same naming conventions and can be done anywhere you set a string or integer. there are many possible syntaxes but the standard one is to use [] and separate each piece of information using ,.
to reference a piece of information in an array, you also use [] with the place in the array it can be found. in the case of a self-numbering array, that's its number.
print_r($myFirstArray[3]);
returns 7, the fourth element in the array (starting from 0).
remember that an array is just a type of variable like an integer or string so you can put an array inside an array.
$mySecondArray = [11, 32, [9, 16, 92], 67, 8, [24, 3], 12];
in this case, $mySecondArray[1] is 32 but $mySecondArray[5] is [24, 3], an array of its own. to access the pieces inside a "nested" array like this, you can use another set of [].
print_r($mySecondArray[5][1]);
returns 3. the values in an array can be treated like any other variables. in this case, you can see they are all integers so they can be used for math.
print_r($mySecondArray[2][0] * $mySecondArray[4]);
returns 72.
of course, it's rare that we already know what the values in an array are all at once. thankfully, we can set those values the same way we just read them.
$vegetables = []; // an empty array called $vegetables
$vegetables[0] = "broccoli";
$vegetables[1] = "potato";
$vegetables[2] = "asparagus";
$vegetables[3] = "cucumber";
$vegetables[4] = "cauliflower";
at this point, $vegetables is "broccoli", "potato", "asparagus", "cucumber", "cauliflower". you certainly don't have to set them all in order but it makes the example easier to follow.
there is a built-in function that allows us to just add another element to the end of an existing array so we don't have to keep track of the numbers. the same code could be written as...
$vegetables = [];
array_push($vegetables, "broccoli");
array_push($vegetables, "potato");
array_push($vegetables, "asparagus");
array_push($vegetables, "cucumber");
array_push($vegetables, "cauliflower");
numbers are often useful when the order of the array is the important part or if the order doesn't matter at all and the array is treated like a list for comparison purposes. sometimes, though, the point is to be able to look things up like in a dictionary. in this case, we can name the elements using strings.
$dictionary = [];
$dictionary["one"] = "a single item";
$dictionary["two"] = "a pair";
$dictionary["three"] = "a trio";
$dictionary["four"] = "a quartet";
$dictionary["five"] = "a quintet";
print_r($dictionary["three"]);
returns a trio.
sometimes we really do know all the information at once -- like in the case of a dictionary -- so we don't need to use a new command for each to set them.
$dictionary = [
"one" => "a single item",
"two" => "a pair",
"three" => "a trio",
"four" => "a quartet",
"five" => "a quintet"
];
don't forget, whitespace is unimportant in php so we can add indentation and new lines anywhere we like to make it easier to read. that same block of code could also be written like this...
$dictionary=["one"=>"a single item","two"=>"a pair","three"=>"a trio","four"=>"a quartet","five"=>"a quintet"];
but that would be much more difficult to read if it becomes a long list. it is not unusual for dictionary lookups to have hundreds or thousands of items so a single line would be a nightmare to find errors in.
the first question you will likely want to ask an array is how many items are inside.
$numbers = [4, 7, 3, 2, 9];
print_r(count($numbers));
returns 5 because $numbers has five items inside.
you have already used array_push to add an item to the end of an array. the same can be done for the beginning of an array with array_unshift.
$numbers = [4, 7, 3, 2, 9];
array_unshift($numbers, 6); // [6, 4, 7, 3, 2, 9]
to take only the beginning of an array...
$numbers = [4, 7, 3, 2, 9];
array_splice($numbers, 3); // [4, 7, 3]
array_splice also allows us to insert or replace elements in an array.
$numbers = [4, 7, 3, 2, 9];
array_splice($numbers, 2, 1, [6, 5, 8]); // [4, 7, 6, 5, 8, 2, 9]
in other words, we start at element 2 and replace 1 element with the contents of the array we included. 3 was replaced by 6, 5, 8 and the rest of the array remained unchanged.
we can also insert elements without replacing any by using a starting position but replacing 0.
$numbers = [4, 7, 3, 2, 9];
array_splice($numbers, 2, 0, [6, 5, 8]); // [4, 7, 6, 5, 8, 3, 2, 9]
in this case, we have started at element 2 and replaced 0 elements with the same contents. as a result, the 3 now remains in our array directly after the values we inserted.
we can also use array_splice to remove items from an array simply by not including anything to replace them with.
$numbers = [4, 7, 3, 2, 9];
array_splice($numbers, 2, 2); // [4, 7, 9]
if you want to remove a single item from either the beginning or end of an array...
$numbers = [4, 7, 3, 2, 9];
array_pop($numbers); // [4, 7, 3, 2]
array_shift($numbers); // [7, 3, 2]
the other common task is to take two arrays and combine them using array_merge.
$a = ["cat", "dog", "mongoose"];
$b = ["tiger", "fox", "anteater"];
$result = array_merge($a, $b); // ["cat", "dog", "mongoose", "tiger", "fox", "anteater"]
we can also combine two arrays in a different way, using one as the names for our elements and the other as the values.
$names = ["fruit", "vegetable", "animal"];
$values = ["apple", "potato", "squirrel"];
$result = array_combine($names, $values); // ["fruit" => "apple", "vegetable" => "potato", "animal" => "squirrel"]
we can also, as you know, substitute arrays for variables.
$names = ["fruits", "vegetables", "animals"];
$values = [
["apple", "banana", "dragonfruit"],
["potato", "cauliflower", "zucchini"],
["squirrel", "mouse", "rat"]
];
$result = array_combine($names, $values); // ["fruits" => ["apple", "banana", "dragonfruit"], "vegetables" => ["potato", "cauliflower", "zucchini"], "animals" => ["squirrel", "mouse", "rat"]]
another common array task is to compare the values in multiple arrays to return those not present using array_diff.
$firstArray = ["a" => "apple", "b" => "berry", "c" => "cherry", "d" => "date", "e" => "eggplant", "f" => "fig"];
$secondArray = ["blueberry", "eggplant", "date", "kiwi", "melon"];
$result = array_diff($firstArray, $secondArray); // ["a" => "apple", "b" => "berry", "c" => "cherry", "f" => "fig"]
only the elements from $firstArray not found in $secondArray were copied into $result.
sometimes you have a list of items as a string and need to separate them into an array. explode makes that possible.
$listAsString = "kitten, puppy, calf, foal, puffling";
$listAsArray = explode(", ", $listAsString); // ["kitten", "puppy", "calf", "foal", "puffling"]
we can do the same in reverse with implode.
$listAsArray = ["kitten", "puppy", "calf", "foal", "puffling"];
$listAsString = implode(", ", $listAsArray); // "kitten, puppy, calf, foal, puffling"
in both cases, the first parameter is a string that separates the items and the second is the source string or array.
remember, spaces inside strings are important. without the spaces, this would be the result.
$listAsString = "kitten, puppy, calf, foal, puffling";
$listAsArray = explode(",", $listAsString); // ["kitten", " puppy", " calf", " foal", " puffling"]
and...
$listAsArray = ["kitten", "puppy", "calf", "foal", "puffling"];
$listAsString = implode(",", $listAsArray); // "kitten,puppy,calf,foal,puffling"
another useful array feature is that any string can be treated as an array of letters.
$country = "zimbabwe";
print_r($country[4]);
returns a (the fifth letter in the string).