How to Create an Array in PHP?

Problem:

You’re looking for a way to create an array.

Solution:

There are two ways you can create an array in PHP.

Method 1: Using array() function

The syntax for creating an array using array() is-

$array_name = array(“index1”=>”value1”, “index2”=>”value2”…);

  • Here, $array_name is the array name. value1, value2 are the values of the array.
  • Here, index could be either of string type or integer type.
  • Indexes are optional. If you don’t mention it, an integer indexes will automatically be generated which increments by 1.

Example 1-

<?php
$week_days = array(“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”);
?>

Here , the array name is $week_days and there are 7 values in it. As we’ve not mentioned the indexes, an auto generating (also auto incrementing by 1) integer indexes have been set. So, index for “Sunday” is 0 and index for “Saturday” is 6.

Example 2-

<?php
$employees = array(“Name” => “John Smith”, “Profession”=>”Web Developer”, “Age” => 28);
?>

Here, the $employees array has string type indexes.

Method 2: Using short array syntax

From PHP 5.4, short array syntax has been introduced. Its syntax is as follows-

$array_name = [
              key1 => value1,
              key2 => value2,
              ---
);

Here, key1, key2 are optional. Omitting the indexes will introduce auto generated integer indexes.

Example
$week_days = [
             0 => “Sunday”,
             1 => “Monday”,
             2 => “Tuesday”
             ];

Method 3: Using [] identifier

The syntax for creating an array using [] identifier is-

$array_name[key] = value;

Here, key is optional. If you don’t mention it, an auto generating integer indexes will be generated.

Example

<?php
$employee[“Name”] = “John Smith”;
$employee[“Profession”] = “Web Developer”;
$employee[“Age”] = 28;
?>