Concept of Array in PHP

 

An array is a special variable that can hold more than one value at a time under a single name.
 
How it Works
If you have a list of fruits, instead of creating three separate variables like $fruit1, $fruit2, and $fruit3, you store them in one array called $fruits.
 
Index (Position)                              Value
[0]                         “Apple”
[1]                      “Banana”
[2]                       “Cherry”

Note: In programming, counting almost always starts at 0, not 1.

 

PHP Code Example

$age = 20;

if ($age < 13) {

    echo “Child”;

} elseif ($age < 20) {

    echo “Teenager”;

} else {

    echo “Adult”;

}

// 1. Create the array

$fruits = array(“Apple”, “Banana”, “Cherry”);

 

// 2. Access a specific item using its index

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

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

 

// 3. Change an item

$fruits[1] = “Mango”;

echo $fruits[1]; // Now outputs: Mango

 

Types of Arrays in PHP
  • Indexed Arrays: Arrays with a numeric index (like the example above).
  • Associative Arrays: Arrays where you use named keys instead of numbers (e.g., "color" => "red").
  • Multidimensional Arrays: Arrays containing other arrays (like a grid or a spreadsheet).