Array in PHP

In PHP, an array is a data structure that can store multiple values under a single variable name. Arrays are one of the most fundamental data types in PHP and are widely used for storing and manipulating collections of data.

There are three main types of arrays in PHP:

  1. Indexed Arrays: Indexed arrays store elements with numeric indices. The index starts from 0 and increments by 1 for each subsequent element. You can access elements in an indexed array using their numeric index.
  2. Example
    $colors = array("Red", "Green", "Blue");
    echo $colors[0]; // Output: Red
  3. Associative Arrays: Associative arrays store elements with named keys (also known as associative keys). Each element is associated with a specific key-value pair. You can access elements in an associative array using their keys.
  4. Example
    $person = array("name" => "John", "age" => 30, "city" => "New York");
    echo $person["name"]; // Output: John
  5. Multidimensional Arrays: Multidimensional arrays are arrays that contain other arrays as their elements. They are useful for storing complex data structures, such as matrices or lists of records.
  6. Example
    $matrix = array(
        array(1, 2, 3),
        array(4, 5, 6),
        array(7, 8, 9)
    );
    echo $matrix[1][2]; // Output: 6

Arrays in PHP are dynamic, which means they can grow or shrink in size dynamically as elements are added or removed. You can use various built-in array functions in PHP to manipulate arrays, such as adding elements, removing elements, sorting elements, merging arrays, and more.

Arrays are versatile and widely used in PHP for tasks such as storing lists of items, managing form data, handling database results, and processing JSON data, among others. Understanding how to work with arrays is essential for PHP developers to effectively manipulate data in their applications.

Next Article ❯