PHP Array with Example

In this article, we learn how to can create and use a PHP array and how you can manipulate array elements using PHP.


PHP Array


PHP Array

PHP arrays are used to store multiple values in a single variable. There are several ways to create and use arrays in PHP. Here are a few examples-


1. Creating an Array

// Method 1: Using array() function
$countries = array("US", "UK", "France", "India");

// Method 2: Using square brackets []
$countries = ["US", "UK", "France", "India"];

Here I have created one array named “countries” and stored some country names.


2. Accessing array elements

// Access the first element of an array
$countries = ["US", "UK", "France", "India"];
echo $countries[1]; // Output: UK

// Access the last element of an array

$last_index = count($countries) - 1;
echo $countries[$last_index]; // Output: India

Pass the array index and access the array elements. The index starts with 0.


3. Modifying array elements

$countries = ["US", "UK", "France", "India"];
// Modifying an element
$countries[1] = "Germany";


#["US", "Germany", "France", "India"]
// Adding an element
$countries[] = "Japan";


Output –

["US", "Germany", "France", "India", "Japan"]


Using the element index you can modify the array element. Add the element in the array using the [] operator.


4. Removing array element

// Remove the last element of an array
unset($countries[count($countries) - 1]);

// Remove an element by its value
$key = array_search("France", $countries);

This is how you can remove elements from the array.


5. Iterating an array in PHP

// Using for loop
for ($i = 0; $i < count($countries); $i++) {
echo $countries[$i] . "\n";

// Using for each loop
foreach ($countries as $country) {
echo $ country . "\n";

You can use for or foreach loop to iterate array elements.


5. Other array functions to play around with an array

$count = count($countries);

// Sort an array in ascending order


// Reverse an array
$countries = array_reverse($countries);

These are just a few examples of how you can use PHP arrays. There are many more array methods available in PHP, and you can use them to manipulate and access the elements of an array easily.


I hope now you are able to create, use and iterate an array in PHP. Also, now you can use different array methods to manipulate PHP array items.

Posted in PHP