PHP arrays


In PHP, arrays are a fundamental data type used to store multiple values in a single variable. They allow you to manage collections of data efficiently and are versatile enough to accommodate a wide range of data structures. PHP supports both indexed and associative arrays.

Types of Arrays in PHP

  1. Indexed Arrays

    Indexed arrays use numeric indexes to access their elements. The index starts from 0 by default.

    Example:

    <?php // Define an indexed array $fruits = array("Apple", "Banana", "Cherry"); // Access elements echo $fruits[0]; // Outputs: Apple echo $fruits[1]; // Outputs: Banana echo $fruits[2]; // Outputs: Cherry ?>

    Creating Indexed Arrays:

    // Using array() function $numbers = array(1, 2, 3, 4, 5); // Using short array syntax (PHP 5.4+) $numbers = [1, 2, 3, 4, 5];
  2. Associative Arrays

    Associative arrays use named keys that you assign to each value, rather than numeric indexes.

    Example:

    <?php // Define an associative array $person = array( "first_name" => "John", "last_name" => "Doe", "age" => 30 ); // Access elements echo $person["first_name"]; // Outputs: John echo $person["last_name"]; // Outputs: Doe echo $person["age"]; // Outputs: 30 ?>

    Creating Associative Arrays:

    // Using array() function $car = array( "make" => "Toyota", "model" => "Camry", "year" => 2022 ); // Using short array syntax (PHP 5.4+) $car = [ "make" => "Toyota", "model" => "Camry", "year" => 2022 ];
  3. Multidimensional Arrays

    Multidimensional arrays are arrays containing other arrays. They can be used to represent more complex data structures like matrices or tables.

    Example:

    <?php // Define a multidimensional array $students = array( array("John", "Doe", 25), array("Jane", "Smith", 22), array("Mike", "Johnson", 30) ); // Access elements echo $students[0][0]; // Outputs: John echo $students[1][1]; // Outputs: Smith echo $students[2][2]; // Outputs: 30 ?>

    Creating Multidimensional Arrays:

    // Using array() function $matrix = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) ); // Using short array syntax (PHP 5.4+) $matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];