Understanding Arrays in PHP


#1

Learn about classes in this article by David Carr who has been developing applications for the web, using mostly PHP, for the past 10 years, and Markus Gray, a full-stack web developer/designer with 11 years of experience and the CEO of Syncware Technologies, Inc.

The basic idea of an array is that it is a variable type, allowing one to store multiple items within a single container. For example, if you wanted to store the names of all employeeworking in a company under the same variable, an array would help you do that.

This article will take you through the various types of arrays and then look at some common operations with them. It will focus on how to store multiple values using arrays. For accessing the code files needed for this article you can go to https://github.com/TrainingByPackt/Beginning-PHP/tree/master/Lesson%202.

Indexed Arrays

Indexed arrays are the most common types of arrays that you will see, and they can be defined as either prepopulated or empty. An empty array can be defined as follows:

<?php $the_array = array(); ?> Note that `$the_array` is a variable. You can use any other variable that you like. Another way to use the shortcut syntax: <?php $the_array = []; ?> If you want to initiate an array with values, you can do so as follows: <?php $students = array("Jill", "Michael", "John", "Sally"); ?> When you initialize an array with prepopulated values, each element gets a numeric index, starting at 0. So, in the preceding example, the index for Jill will be 0, the index for Michael will be 1, the index for John will be 2, and the index for Sally will be 3. In order to print out the first index of the `students` array, you can use the following code: <?php echo $students[0]; ?> Usually, when you use an array, you want to add to it throughout the course of your program. This can be done in one of two ways: The `append` shortcut: <?php $students[] = "Tom"; ?> Or you can use the `array` _ `push` function: <?php array_push($students, "Tom", "Joey"); ?> Typically, the shortcut method is used by developers; if you want to push multiple records to an array at a time, you can use the `array_push` function. Sometimes, you'll have an element in an array that needs to be removed. To remove an element from an array, use the `unset` function. In the following example, you’ll remove "Tom" from the array: <?php unset($students[4]); ?> To update an element, do the following: <?php $students[0] = "Jessie"; ?> Associative Arrays Next are associative arrays, better known as key-value pairs. With associative arrays, you can use text-based keys to store your values, which can be helpful in specific cases. For example, if you take one of the students from the preceding examples (in this case, Michael), you can store his `age` , `gender` , and `favorite color, ` as shown here: <?php $michael = array( "age" => 20, "gender" => "male", "favorite_color" => "blue" ); ?> If you need to access a specific value in the array, you can use the `key` . For example, if you want to print Michael's age, do the following: <?php echo $michael['age']; ?> Adding data to an `associative` array is just as easy as adding data to an indexed array. You can simply use the key and assign a value. Suppose that you want to add an occupation to Michael's array: <?php $michael["occupation"] = "sales associate"; ?> To remove an element from an associative array, follow the same steps as the `indexed` arrays, but this time, use the key. Remove the occupation added in the last step: <?php unset($michael['occupation']); ?> Working with Arrays In this section, include `name` , `age` , `location` , and `education level` . Follow these steps: * Open your code editor and create a new file, `arrays.php.` * Within the new file, create your open and close `php` tags: <?php ?> Now, create a new variable, called `$myinfo,` and initialize it with a new array: <?php $myinfo = array(); ?> ``` ``` * Then, populate the new array with your `name` , `age` , `location` , and `education level` . * Next, print your data: <?php $myinfo = array("John", 25, "USA", "College"); echo "My name is " . $myinfo[0] . "\n"; echo "I am ". $myinfo[1] . " years old. \n"; echo "I live in " . $myinfo[2] . "\n"; echo "My latest education level is " . $myinfo[3]; ?> ``` ``` Open your working directory in the Terminal and type the following command: ``` php ``` ``` arrays.php ``` You will get a result as displayed in the following output: ``` My name is John. ``` ``` I am 25 years old. ``` ``` I live in USA. ``` ``` My latest education level is College. ``` Converting a String into an Array Sometimes, when you're building a PHP-based application, you don't instantiate an array with a predefined set of data - which is the case when building a utility script, for example. Suppose you have a variable with the string version of a filename, and you want to get the name of the file without the extension. This task can be done easily using the `explode` function. The `explode` function takes two arguments: the delimiter and the string that you want to convert into an array. `Explode` function takes two arguments: <?php $filename = "myexamplefile.txt"; $filename_parts = explode(".", $filename); echo "Your filename is " . $filename_parts[0]; ?> In the preceding example, you define a filename variable, and then, using the explode function, you break the string into its parts with the period delimiter. The `$filename_parts` variable contains an array of two elements, the first being the string `myexamplefile` and the second containing the string `txt` . Knowing this, you can print out the filename by accessing the 0 index of the array of string parts. Merging an Array into a String Along with the `explode` function, PHP also gives you a function that allows you to do the exact opposite: the `implode` function. When you want to take an existing array and convert it into a string, you can use the implode function to define a delimiter and pass it the array; you'll get a single string as a result. Now, go back to the `explode` example. Suppose that you have a filename and want to append some other string to the end of it before saving it back to a string: <?php $filename = "myexamplefile.txt"; $filename_parts = explode(".", $filename); $filename_parts[0] .= "_v1"; $filename = implode(".", $filename_parts); echo "Your new filename is " . $filename; ?> In the preceding code example, you started off using the explode function to break your original filename into its parts. You then access the filename portion and append the string _v1 to the end of it. Using the implode function, you recombine the filename using its parts, and finally, print it back to the screen for the user to see. Slicing Arrays Another `array_slice` function; by default, the function requires only two arguments, but it can take four. The two required arguments are the array itself and the starting point for the new array. The two optional arguments are the length of (or a number of elements to include in) the new array and the preserve option. The preserve option allows you to decide whether the current array elements should remain the same or be reordered after the split. Here's a basic usage example: <?php $fruit = array("apples","grapes", "oranges", "lemons","limes"); $smallerFruitArray = array_slice($fruit, 2); ?> In the preceding example, when you run the fruit array through `array_slice,` you’ll get an array containing oranges, lemons, and limes. Sorting an Array Sorting is another important tool for building certain types of programs. One of the sorting functions that you'll often see in PHP is the `ksort` function. `ksort` allows you to pass an array in as an argument, and then sort it in ascending order. An example of how to use it is as follows: <?php $people = array("Jessica" => "35", "April" => "37", "John" => "43", "Tom" => 25); ksort($people); ?> In the preceding example, you have an array of people. Once you put the people array through the `ksort` function, you should see the names in alphabetical order. Multidimensional Arrays The next type is the `multidimensional` array. Multidimensional arrays are simply arrays within arrays. In your previous examples of arrays, you stored a student's name. What happens when you want to store multiple details for a specific student? This is where multidimensional arrays come in. Now, look at how you can define a student array that also stores the student's `gender` and `favorite` `color` : <?php $students = array( "Jill" => array( "age" => 20, "gender" => "female", .... "Amy" => array( "age" => 25, "gender" => "female", "favorite_color" => "green" ), ); ?> If you want to access a student's information, use the following key: ``` ``` <?php echo $students['Jill']['age']; ?> The preceding example will print out Jill's age. With multidimensional arrays, you update element values in pretty much the same way you do when using one-dimensional arrays. For example, if you want to change Jill's age to `21,` do the following: <?php $students['Jill']['age'] = 21; ?> Including an Array of Hobbies in Your Project In this section, you can expand on the previous example to include an array of hobbies: * Open your code editor and create a new file, `multidimensional.php` . * Within the new file, create your open and close `php` tags. * Create a new variable called `$` `user,` and initialize it with a new array: <?php ?> ``` ``` <?php $user = array(); ?> Populate the new array with two main sections: `info` and `hobbies` . In the info array, store the `name` , `age` , `location,` and `education level` , and in the `hobbies` array, store three hobbies. <?php $user = array( "info" => array( "name" => "john", "age" => 27, ... ) ); ?> Now print your data: <?php$user = array( "info" => array( "name" => "john", "age" => 27, "location" => "USA", ..... echo "I live in " . $user["info"]['location'] . ".\n"; echo "My latest education level is " . $user['info']['education_level']. ".\n"; echo "I enjoy " . $user["hobbies"][0] . ", " . $user["hobbies"] [1] . ", " . $user["hobbies"][2].".\n"; ?> Open your working directory in the Terminal and type the following command: ``` php ``` ``` multidimensional.php ``` You will get a result based on the input that you provided in the preceding array. *If you found this article interesting, you can explore* [ *Beginning PHP* ]([https://www.amazon.com/Beginning-PHP-features-embrace-development/dp/1789535905](https://www.amazon.com/Beginning-PHP-features-embrace-development/dp/1789535905)) *to learn all the fundamentals of PHP with a book that blends theory with practice to build up the skills you need for modern web development.* [ *Beginning PHP* ]([https://www.packtpub.com/application-development/beginning-php](https://www.packtpub.com/application-development/beginning-php)) *will help you with everything you need to get up and running with the latest version of PHP.*

#2

That is way too long for a forum post, organize it. Pretty good though!