PHP Working With Arrays

PHP Code Snippets Working With Arrays


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.



//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:";

//Remove an element from the end of an array.
echo "Remove element:";

//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:";

//Reverse the array.
echo "Reverse array:";

//Remove duplicates in an array.
$allNumbers = array_unique($allNumbers);
echo "Remove duplicates:";

//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:";


//Prints array so we can see what is inside it..
function printArray($arr){
    echo "<pre>";
    echo "</pre>";


Resulting Output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger