About
In this code snippet, we’ll learn how to work with arrays in PHP.
More specifically we’ll learn how to merge arrays, add/remove elements, reverse the array, remove duplicates, search the array, find its length, make associative arrays and get their keys. Associative arrays are use strings for indexes instead of numbers.
Note: I covered just the array functions I found myself using the most. Here is the full list of array functions.
Let’s see the code example below.
Code:
<?php //1. way to make an array in PHP. $numbers = array( 1, 1, 2 ); //2. way to make an array. $numbers2 = [ 4, 5, 6 ]; //Add element to the end of an array. array_push($numbers, 3); echo "Add element:"; printArray($numbers); //Remove an element from the end of an array. array_pop($numbers2); echo "Remove element:"; printArray($numbers2); //Get the number of elements in the array. echo "Number of elements:"; echo count($numbers); echo "<br>"; //Merge arrays. $allNumbers = array_merge($numbers, $numbers2); echo "Merge arrays:"; printArray($allNumbers); //Reverse the array. array_reverse($allNumbers); echo "Reverse array:"; printArray($allNumbers); //Remove duplicates in an array. $allNumbers = array_unique($allNumbers); echo "Remove duplicates:"; printArray($allNumbers); //Search array for element and return its index. echo "Index of number 4:"; echo array_search(4, $allNumbers); //Make an associative array with key value pairs. $keyValuePairs = [ "Bob" => "15258", "Alice" => "15892" ]; //List the keys of an array. echo "List array keys:"; printArray(array_keys($keyValuePairs)); ///////////////////////////////////////////////////////// //Prints array so we can see what is inside it.. function printArray($arr){ echo "<pre>"; print_r($arr); echo "</pre>"; } ///////////////////////////////////////////////////////////