PHP Working With Arrays

PHP Code Snippets Working With Arrays
Share:

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>";
}

///////////////////////////////////////////////////////////

Resulting Output:

Share:

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