Create an Array in PHP

In PHP, you can create an array in several ways. Here are a few examples:

  1. Using the array() function:
$fruits = array("apple", "banana", "orange", "mango");

In this example, we create an array of fruits with four elements.

  1. Using square brackets:
$numbers = [1, 2, 3, 4, 5];

In this example, we create an array of numbers with five elements.

  1. Creating an empty array and adding elements to it:
$students = [];
$students[] = "John";
$students[] = "Jane";
$students[] = "Michael";

In this example, we create an empty array called $students and then add three elements to it.

  1. Associative arrays:
$person = array(
    "name" => "John Doe",
    "age" => 30,
    "occupation" => "Web Developer"
);

In this example, we create an associative array called $person with three key-value pairs.

Note that in PHP, arrays can contain elements of different data types. Also, array keys can be either integers or strings.

Scroll to Top