![]() This is always a good idea if you think you might want to use the variable later in the script in a different context. Notice that the script calls unset() to delete the $director variable after it’s been used as a reference in the first loop. ![]() List( $firstName, $lastName ) = explode( " ", $director ) Change the name format for each element to "last, first" It’s a bit like a shortcut in Windows, or an alias in Mac OS.įor example, the following script loops through each director in the $directors array, and uses PHP’s explode() function and list construct to reverse the director’s first and last names: $value then becomes a reference to the element value in the original array, which means you can change the element by assigning a new value to $value.Ī reference is a pointer to the original value, rather than a copy of the value. ![]() You do this by placing an ampersand ( &) before the value variable in the foreach construct: To change array values, you need to reference the values. This is because foreach works on a copy of the array values, rather than the original array. However, if you do this you’ll find that your array values aren’t changed. So far you’ve just looked at reading element values, but what if you want to change values as you loop through? You might try something like this: $movie = array( "title" => "Rear Window", Here’s an example that loops through an associative array of movie information, displaying each element’s key and value inside an HTML definition list: Luckily, foreach gives you a way to do just that: So far so good, but what about associative arrays? With these types of arrays, you often want to access each element’s key as well as its value. The above script produces the following output: $directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ) This code runs after the loop finishesįor example, the following script loops through a list of movie directors in an indexed array, displaying each director’s name as it goes: The simplest way to use foreach is when looping through the values in an indexed array. In this article you learn the basic syntax of foreach, and see how to use it to loop through both indexed and associative arrays. However, there’s a much easier way to loop through arrays: the foreach construct. In Counting PHP Array Elements Using count(), I showed how you can use a for loop along with the count() function to loop through an array. For example, you may want to display each value in an HTML table, or give each element a new value. Often you need to move through all the elements in a PHP array so that you can do something with each element’s value.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |