Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

What is Array?

An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values. To create an array in PHP, we use the array function array( ). By default, an array of any variable starts with the 0 index.

There are three types of arrays:

  1. Indexed array
  2. Associative array
  3. Multidimensional array

Indexed array: These are arrays where each element is assigned a numeric index starting from 0. Indexed arrays are the most common type of array in PHP.

Example:

PHP
<?php

$fruits = array("Apple", "Banana", "Orange");

// or using short array syntax:

// $fruits = ["Apple", "Banana", "Orange"];

echo $fruits[0]; // Outputs: Apple

echo $fruits[1]; // Outputs: Banana

echo $fruits[2]; // Outputs: Orange

?>

Associative Arrays: In associative arrays, elements are assigned key-value pair, where each value is associated with a unique key.

Example:

PHP
<?php

$person = array("name" => "John", "age" => 30, "city" => "New York");

echo $person["name"]; // Outputs: John

echo $person["age"];  // Outputs: 30

echo $person["city"]; // Outputs: New York

?>

Multidimensional arrays: These are arrays that contain other arrays as elements. Multidimensional arrays can be used to represent complex data structures such as matrices or tables.

Example:

PHP
<?php

$matrix = array(

    array(1, 2, 3),

    array(4, 5, 6),

    array(7, 8, 9)

);

echo $matrix[1][2]; // Outputs: 6

?>

For Each:

The foreach loop in PHP construct produces the most comfortable way to iterate the array components. It runs on arrays and objects both.  The foreach loop iterates over an array of entities; the enactment is streamlined and completes the loop in a limited time comparatively.

The basic syntax:

PHP
<?php

foreach ($array as $value) {

    // Code to be executed for each element

    // $value represents the current element being iterated

}

?>

‘$array’ is the array you want to iterate over.

‘$value’ is a variable that represents the value of the current element in each iteration. You can name this variable anything you want.

Example:

PHP
<?php

$colors = array("Red", "Green", "Blue");

foreach ($colors as $color) {

    echo $color . " ";

}

// Outputs: Red Green Blue

?>