PHP Array Functions and Examples

Indexed Array in PHP

An indexed array in PHP is an array where each element is assigned a numeric index, starting from 0 by default.

Example:

// Indexed array
$fruits = ["apple", "banana", "orange"];

// Accessing elements by index
echo $fruits[0]; // Output: apple
echo $fruits[1]; // Output: banana
echo $fruits[2]; // Output: orange

In this example:

  • $fruits is an indexed array where “apple” is at index 0, “banana” is at index 1, and “orange” is at index 2.
  • You can access elements in the array using their numeric index, like $fruits[0] to get “apple”.

Using foreach with an Indexed Array:

$fruits = ["apple", "banana", "orange"];

foreach ($fruits as $index => $fruit) {
    echo "Index $index: $fruit\n";
}

Output:

Index 0: apple
Index 1: banana
Index 2: orange

This example demonstrates how to iterate over an indexed array using a foreach loop, where $index holds the index of the current element and $fruit holds the value.

1. array_push()

  • Description: Adds one or more elements to the end of an array.
  • Example:
  $fruits = ["apple", "banana"];
  array_push($fruits, "orange", "grape");
  print_r($fruits);

Output:

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

2. array_pop()

  • Description: Removes the last element of an array.
  • Example:
  $fruits = ["apple", "banana", "orange"];
  array_pop($fruits);
  print_r($fruits);

Output:

  Array ( [0] => apple [1] => banana )

3. array_shift()

  • Description: Removes the first element of an array.
  • Example:
  $fruits = ["apple", "banana", "orange"];
  array_shift($fruits);
  print_r($fruits);

Output:

  Array ( [0] => banana [1] => orange )

4. array_reverse()

  • Description: Returns an array with elements in reverse order.
  • Example:
  $fruits = ["apple", "banana", "orange"];
  $reversed = array_reverse($fruits);
  print_r($reversed);

Output:

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

5. count()

  • Description: Counts all elements in an array.
  • Example:
  $fruits = ["apple", "banana", "orange"];
  echo count($fruits);

Output:

  3

Short Array Syntax

  • Description: PHP allows the use of a short array syntax which uses square brackets [] instead of the older array() syntax.
  • Example:
  $fruits = ["apple", "banana", "orange"];

This is equivalent to the old syntax:

  $fruits = array("apple", "banana", "orange");

Combined Example

Here’s a combined example using multiple array functions:

  $fruits = ["apple", "banana", "orange"];

  // Add elements
  array_push($fruits, "grape", "pear");

  // Remove the last element
  array_pop($fruits);

  // Remove the first element
  array_shift($fruits);

  // Reverse the array
  $reversed = array_reverse($fruits);

  // Count the elements
  echo "Number of fruits: " . count($reversed) . "\n";

  print_r($reversed);

Output:

  Number of fruits: 2
  Array ( [0] => orange [1] => grape )

Associative Array in PHP

An associative array in PHP is an array where each key is associated with a specific value. Unlike indexed arrays, which use numeric indices, associative arrays use named keys to identify values.

Example:

  $person = [
      "name" => "John",
      "age" => 30,
      "city" => "New York"
  ];

  // Accessing values
  echo $person["name"]; // Output: John
  echo $person["age"];  // Output: 30

Using print_r to print the entire associative array:

  $person = [
      "name" => "John",
      "age" => 30,
      "city" => "New York"
  ];

  print_r($person);

Output:

  Array
  (
      [name] => John
      [age] => 30
      [city] => New York
  )

Using foreach to print each key-value pair:

  $person = [
      "name" => "John",
      "age" => 30,
      "city" => "New York"
  ];

  foreach ($person as $key => $value) {
      echo "$key: $value\n";
  }

Output:

  name: John
  age: 30
  city: New York

Useful Functions for Associative Arrays

1. array_keys()

  • Description: Returns all the keys of an associative array.
  • Example:
  $person = ["name" => "John", "age" => 30, "city" => "New York"];
  $keys = array_keys($person);
  print_r($keys);

Output:

  Array ( [0] => name [1] => age [2] => city )

2. array_values()

  • Description: Returns all the values of an associative array.
  • Example:
  $person = ["name" => "John", "age" => 30, "city" => "New York"];
  $values = array_values($person);
  print_r($values);

Output:

  Array ( [0] => John [1] => 30 [2] => New York )

3. array_flip()

  • Description: Flips the keys and values of an associative array, making the keys the values and the values the keys.
  • Example:
  $person = ["name" => "John", "age" => 30, "city" => "New York"];
  $flipped = array_flip($person);
  print_r($flipped);

Output:

  Array ( [John] => name [30] => age [New York] => city )

4. array_reverse()

  • Description: Returns an array with the elements in reverse order. Works for both indexed and associative arrays.
  • Example:
  $person = ["name" => "John", "age" => 30, "city" => "New York"];
  $reversed = array_reverse($person);
  print_r($reversed);

Output:

  Array ( [city] => New York [age] => 30 [name] => John )

Multidimensional Arrays in PHP

A multidimensional array is an array that contains one or more arrays as its elements. These arrays can be of any depth, meaning you can have arrays within arrays within arrays.

Example of a 2D (Two-Dimensional) Array:

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

// Accessing elements
echo $matrix[0][0]; // Output: 1
echo $matrix[1][2]; // Output: 6
echo $matrix[2][1]; // Output: 8

Example of a 3D (Three-Dimensional) Array:

$cube = [
    [
        [1, 2], [3, 4]
    ],
    [
        [5, 6], [7, 8]
    ]
];

// Accessing elements
echo $cube[0][1][0]; // Output: 3
echo $cube[1][0][1]; // Output: 6

Useful Functions for Multidimensional Arrays

1. array_merge_recursive()

  • Description: Merges two or more arrays into one array. If the arrays have the same keys, the values are merged into arrays themselves.
  • Example:
  $array1 = [
      "numbers" => [1, 2],
      "letters" => ["a"]
  ];

  $array2 = [
      "numbers" => [3, 4],
      "letters" => ["b", "c"]
  ];

  $result = array_merge_recursive($array1, $array2);
  print_r($result);

Output:

  Array
  (
      [numbers] => Array
          (
              [0] => 1
              [1] => 2
              [2] => 3
              [3] => 4
          )

      [letters] => Array
          (
              [0] => a
              [1] => b
              [2] => c
          )

  )

2. array_map()

  • Description: Applies a callback function to the elements of the given arrays.
  • Example:
  $matrix = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
  ];

  $squared = array_map(function($row) {
      return array_map(function($element) {
          return $element * $element;
      }, $row);
  }, $matrix);

  print_r($squared);

Output:

  Array
  (
      [0] => Array
          (
              [0] => 1
              [1] => 4
              [2] => 9
          )

      [1] => Array
          (
              [0] => 16
              [1] => 25
              [2] => 36
          )

      [2] => Array
          (
              [0] => 49
              [1] => 64
              [2] => 81
          )
  )

3. array_column()

  • Description: Returns the values from a single column of the input array.
  • Example:
  $students = [
      ["name" => "Alice", "age" => 20],
      ["name" => "Bob", "age" => 22],
      ["name" => "Charlie", "age" => 23]
  ];

  $names = array_column($students, "name");
  print_r($names);

Output:

  Array
  (
      [0] => Alice
      [1] => Bob
      [2] => Charlie
  )

4. array_walk_recursive()

  • Description: Applies a user-defined function to every element of an array, including elements within nested arrays.
  • Example:
  $matrix = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
  ];

  array_walk_recursive($matrix, function(&$value) {
      $value += 10;
  });

  print_r($matrix);

Output:

  Array
  (
      [0] => Array
          (
              [0] => 11
              [1] => 12
              [2] => 13
          )

      [1] => Array
          (
              [0] => 14
              [1] => 15
              [2] => 16
          )

      [2] => Array
          (
              [0] => 17
              [1] => 18
              [2] => 19
          )
  )

These examples demonstrate how you can use multidimensional arrays in PHP and some of the functions available to manipulate them.

Share on :

Recent Post

© 2024 All rights reserved by Go1digital.com