Anyways, one action you might want a function to do is return a value. To do this you may have a function fetch results from a database or perform some equation base on a value being passed to the function. For example I could make a function that adds 10 to a value.
function addTen($number) {In the above example I have a function called addTen that is passed a number and returns that number with 10 added to it. In order to have the code spit out the value you just echo out the function. Pretty simple
$sum = $number + 10;
return $sum;
}
echo addTen(5);
Returning Multiple Values
A function returning one variable is easy. Functions are meant to return a variable. Having a function return multiple variables is a little more complicated. The way it is achieved is with an array.Arrays are variables with multiple values. An example of an array might be a variable called $color. There are many colors, so it would make sense to create our variable $color using an array. To make an array you declare the variable and specify the values like so: $color = array(red,blue,green,black); You access the values by specifying the key (Pointing at which value you want). To access red you would: echo $color[0]; Arrays start with 0 as the first value. Another type of array are associative arrays. These types of arrays have user defined keys instead of the default numbered keys. For example I could have and array of the traits of a person: $person = array( 'name' => 'Jason', 'address' => '123 Main St.', 'age' => '25'); To access Jason's address you would echo $person['address'];
So that brings us to the main objective here: Creating a function that returns multiple values.
// This is handy if you had a function that could do a database call and return a bunch of values. You could then access those values as an arrayThis method has all sorts of uses. This is extremely useful when dealing with a database and you want to consolidate your fetch operations in a function but want to separate your styling code from the function.
function animals() {
$dog = "odie";
$cat = "garfield";
$rabbit = "bugs";
$donkey = "eeyore";
$animals = array (
dog => $dog,
cat => $cat,
rabbit => $rabbit,
donkey => $donkey
);
return $animals;
}
// set variable equal to the function returning the array
$animals = animals();
//access the values through the keys of the array
echo $animals['dog'];
echo "
";
echo $animals['cat'];
echo "
";
Hope you find this useful!
No comments:
Post a Comment