WikiGalaxy

Personalize

PHP Arrays

Indexed Arrays:

Indexed arrays are arrays with a numeric index. These are the most common type of array in PHP and are used to store a list of items.


$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Outputs: Apple
      

Console Output:

Apple

Associative Arrays

Associative Arrays:

Associative arrays use named keys that you assign to them. This is useful for storing data in key-value pairs.


$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
echo $ages['Ben']; // Outputs: 37
      

Console Output:

37

Multidimensional Arrays

Multidimensional Arrays:

Multidimensional arrays contain one or more arrays. These are often used to store data in a tabular form.


$cars = array(
  array("Volvo", 22, 18),
  array("BMW", 15, 13),
  array("Saab", 5, 2),
  array("Land Rover", 17, 15)
);
echo $cars[0][0]; // Outputs: Volvo
      

Console Output:

Volvo

Array Functions

Array Functions:

PHP provides a variety of functions to manipulate arrays, such as sorting, merging, and slicing.


$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
print_r($numbers); // Outputs: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 11 [4] => 22 )
      

Console Output:

Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 11 [4] => 22 )

Array Length

Array Length:

You can find the length of an array using the count() function, which returns the number of elements in an array.


$fruits = array("Apple", "Banana", "Cherry");
echo count($fruits); // Outputs: 3
      

Console Output:

3

Array Push

Array Push:

The array_push() function adds one or more elements to the end of an array.


$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack); // Outputs: Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )
      

Console Output:

Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )

Array Merge

Array Merge:

The array_merge() function merges one or more arrays into one array.


$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
// Outputs: Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )
      

Console Output:

Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )

Array Slice

Array Slice:

The array_slice() function extracts a slice of an array, allowing you to retrieve a subset of elements.


$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // Starts from index 2
print_r($output); // Outputs: Array ( [0] => c [1] => d [2] => e )
      

Console Output:

Array ( [0] => c [1] => d [2] => e )

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025