HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Arrays

An array is a special variable that can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$car1 = "Volvo";
$car2 = "BMW";
$car3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? What if you had 300 cars? The solution is an Array!


1. Creating an Array

In PHP, arrays can be created using the array() function or the shorter square bracket [] syntax.

<?php
    $cars = array("Volvo", "BMW", "Toyota");
    // OR
    $cars = ["Volvo", "BMW", "Toyota"];
?>

2. Types of Arrays in PHP

There are three main types of arrays that you will use frequently:

  • Indexed Arrays: Arrays with a numeric index (starting from 0).
  • Associative Arrays: Arrays with named keys (like a dictionary).
  • Multidimensional Arrays: Arrays containing one or more arrays.

3. Array Length: count()

The count() function is used to return the number of elements currently stored in an array.

<?php
    $cars = ["Volvo", "BMW", "Toyota"];
    echo count($cars); // Outputs: 3
?>
Zero-Based: Remember that in PHP (and most languages), the index of an array always starts at 0, not 1. The first item is $array[0].
Pro Tip: Arrays in PHP are dynamic. You don't need to specify a size when you create them; you can just keep adding elements as needed.

Key Points to Remember

  • An array groups multiple pieces of data into one variable.
  • Create arrays using array() or the newer [] syntax.
  • Access elements using their index or key.
  • The count() function tells you how many items are in the array.
  • Arrays can hold any data type, including other arrays.