If you're looking to get to grips with the powerful array functionality in PHP, you've come to the right place. This guide covers all the basics of using arrays in PHP, including creating an array, looping through it, sorting its elements, and processing them and become a better PHP developer.
Also Read: Top 10 reasons to choose Laravel
Create PHP Arrays
When creating an array in PHP, you can use either the
array() constructor function or the square bracket syntax. Let's think about a simple example - we want to create an array that stores a list of names. The first way to do this is with
$names = array('John', 'Sam', 'Harry');
We can also achieve the same result with brackets:
$names = ['John', 'Sam', 'Harry'];
Sort Arrays Alphabetically or Numerically
Also Read: Top 6 Security Tips for a PHP Application
Sorting your array elements can be useful in some cases. To sort an array alphabetically or numerically, the PHP
asort() functions can come in handy.
usort() will sort an array based on a user-defined comparison function, and
asort() will sort the array by its values instead of its keys. Both functions accept an array as their argument and return the sorted version of it. Let's see how these work:
Add and Remove Array Elements Dynamically
One of the most frequent operations done with PHP arrays is adding and deleting elements. Fortunately, there are functions that can help you do this. The array_push() function allows you to push an item into any array, while the
array_pop() function pops an item off of it. If you need to remove a specific element from an array, you can use the unset function which accepts the index of the element as its argument and removes it from the array.
Use Multidimensional Arrays for More Complex Data Storage
PHP multidimensional arrays can allow you to store more complex data than a single-dimensional array. This type of array is used when the data is organized into sub-lists within the main list. It’s helpful for storing multiple related pieces of information in an easy access format. The syntax for creating a multidimensional array looks like this:
$multi_array =[ ['john'], ['sam'] ];
Iterate Through 2D PHP Arrays With Nested For Loops
If you want to iterate through every element in your multidimensional array, you can use a nested loop statement. The outer loop is used to access each element of the main array while the inner loop moves through all the subarrays. When working with nested arrays, it’s important to remember the structure of the data when constructing your loops. Here is an example of a for loop that iterates over an array containing two-dimensions:
Also Read: Composer PSR4 Autoloading
for ($i = 0; $i < count($multi_array); $i++) for ($j = 0; $j < count($multi_array); $j++ ) echo "Element ".$multi_array."n";