PHP Arrays

Arrays in PHP are used to store multiple values in a single variable.

Types of Arrays

PHP supports two types of arrays:

  • Indexed Arrays: Arrays with a numeric index.
  • Associative Arrays: Arrays with a string index.

Example of PHP Indexed Arrays

<?php
$colors = array("red", "green", "blue");

echo $colors[0] . "\n";
// Outputs: red
echo $colors[1] . "\n";
// Outputs: green
echo $colors[2] . "\n";
// Outputs: blue
?>

Output:

red
green
blue

Explanation: This example demonstrates the use of indexed arrays in PHP. The array is defined with three elements, and each element is accessed using its numeric index.

Example of PHP Associative Arrays

<?php
$person = array("name" => "John", "age" => 30);

echo $person['name'] . "\n";
// Outputs: John
echo $person['age'] . "\n";
// Outputs: 30
?>

Output:

John
30

Explanation: This example demonstrates the use of associative arrays in PHP. The array is defined with two elements, and each element is accessed using its string index.