HOME HTML EDITOR C JAVA PHP

PHP Arrays

An array stores multiple values in one single variable. It is a special variable which can hold more than one value at a time, making it easier to manage related data.

1. Create an Array

In PHP, the array() function is used to create an array. You can also use the short array syntax [].

<?php
  $cars = array("Volvo", "BMW", "Toyota");
  echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

2. Indexed Arrays

Arrays with a numeric index. The index always starts at 0.

<?php
  $colors = ["Red", "Green", "Blue"];
  echo $colors[1]; // Outputs: Green
?>

3. Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

<?php
  $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
  echo "Peter is " . $age['Peter'] . " years old.";
?>

4. Multidimensional Arrays

An array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.

<?php
  $cars = array (
    array("Volvo",22,18),
    array("BMW",15,13),
    array("Saab",5,2)
  );

  echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".";
?>

5. Useful Array Functions

PHP has many built-in functions for arrays, such as count(), sort(), and array_merge().

<?php
  $cars = array("Volvo", "BMW", "Toyota");
  echo count($cars); // Outputs: 3

  sort($cars); // Sorts the array alphabetically
?>
Tip: Use the foreach loop when you want to iterate through all the values of an array. It is the most efficient way to handle array data.