Home >Backend Development >PHP Tutorial >What is an array in PHP? How do you create and access elements in it?

What is an array in PHP? How do you create and access elements in it?

Johnathan Smith
Johnathan SmithOriginal
2025-03-19 11:39:28966browse

What is an array in PHP? How do you create and access elements in it?

An array in PHP is a data structure that stores multiple values in a single variable. It can hold elements of any data type, including other arrays. Arrays in PHP are versatile, supporting both indexed and associative arrays.

To create an indexed array, you can use the following methods:

  1. Using the array() function:

    <code class="php">$fruits = array("apple", "banana", "orange");</code>
  2. Using the short array syntax (PHP 5.4 ):

    <code class="php">$fruits = ["apple", "banana", "orange"];</code>

To create an associative array, you use keys along with the values:

<code class="php">$person = array("name" => "John", "age" => 30, "city" => "New York");</code>

To access elements in an array:

  • For indexed arrays, you access elements using their numeric index (starting from 0):

    <code class="php">echo $fruits[0]; // Outputs: apple</code>
  • For associative arrays, you access elements using their keys:

    <code class="php">echo $person["name"]; // Outputs: John</code>

What are the different types of arrays available in PHP?

PHP supports three types of arrays:

  1. Indexed Arrays:
    These are arrays with numeric indexes. The index starts from 0 by default and can be assigned manually.

    <code class="php">$colors = array("red", "green", "blue");</code>
  2. Associative Arrays:
    These are arrays with named keys. Each key is associated with a value.

    <code class="php">$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);</code>
  3. Multidimensional Arrays:
    These are arrays that contain one or more arrays within them. They can be indexed, associative, or a mixture of both.

    <code class="php">$students = array(
        "student1" => array(
            "name" => "John",
            "age" => 20
        ),
        "student2" => array(
            "name" => "Jane",
            "age" => 22
        )
    );</code>

How can you manipulate and modify elements within a PHP array?

You can manipulate and modify elements within a PHP array using various techniques:

  1. Adding Elements:

    • For indexed arrays, you can use the [] operator to add elements to the end of the array:

      <code class="php">$fruits[] = "grape";</code>
    • For associative arrays, you can assign values to new keys:

      <code class="php">$person["job"] = "Developer";</code>
  2. Modifying Elements:

    • Change the value of an existing element:

      <code class="php">$fruits[1] = "kiwi"; // Changes "banana" to "kiwi"
      $person["age"] = 31; // Changes John's age to 31</code>
  3. Removing Elements:

    • Use the unset() function to remove a specific element:

      <code class="php">unset($fruits[2]); // Removes "orange"
      unset($person["city"]); // Removes the "city" key and its value</code>
  4. Reordering Elements:

    • The array_values() function can be used to reset the numeric keys of an array after deletions:

      <code class="php">$fruits = array_values($fruits);</code>

What functions can you use to iterate over a PHP array?

PHP provides several functions to iterate over arrays:

  1. foreach Loop:
    The most common way to iterate over an array is using a foreach loop. It works with both indexed and associative arrays.

    <code class="php">foreach ($fruits as $fruit) {
        echo $fruit . "<br>";
    }
    
    foreach ($person as $key => $value) {
        echo $key . ": " . $value . "<br>";
    }</code>
  2. array_map() Function:
    This function applies a callback to the elements of given arrays.

    <code class="php">$uppercaseFruits = array_map('strtoupper', $fruits);</code>
  3. array_walk() Function:
    This function applies a user-defined callback function to each element of the array.

    <code class="php">array_walk($fruits, function($value, $key) {
        echo "$key: $value<br>";
    });</code>
  4. array_reduce() Function:
    This function iteratively reduces the array to a single value using a callback function.

    <code class="php">$sum = array_reduce($numbers, function($carry, $item) {
        return $carry   $item;
    }, 0);</code>
  5. array_filter() Function:
    This function filters elements of an array using a callback function.

    <code class="php">$evenNumbers = array_filter($numbers, function($value) {
        return $value % 2 == 0;
    });</code>

These functions provide flexible ways to manipulate and iterate over arrays in PHP, catering to various use cases and requirements.

The above is the detailed content of What is an array in PHP? How do you create and access elements in it?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn