PHP Create Array using Square Bracket

Description

We can create an array from scratch simply by creating its elements using the square bracket syntax.

Syntax

For indexed arrays


$arrayName[] = new value
$arrayName[] = new value

For associative arrays


$arrayName["new Key"] = new value
$arrayName["new Key2"] = new value2

Example 1

The following three examples all produce exactly the same array:

Creating an array using the array() construct

$authors1 = array( "Java", "PHP", "CSS", "HTML" );

Creating the same array using [] and numeric indices


$authors2[0] = "Java"; 
$authors2[1] = "PHP"; 
$authors2[2] = "CSS"; 
$authors2[3] = "HTML"; 

Creating the same array using the empty [] syntax


$authors3[] = "Java"; 
$authors3[] = "PHP"; 
$authors3[] = "CSS"; 
$authors3[] = "HTML";   

Example 2

Since the square bracket can also append value to the end of an array. We can avoid append value to the existing array by clear the existing array first with array() function.


$authors = array();   

This creates an array with no elements (an empty array). We can then go ahead and add elements later:

 
$authors[] = "Java"; 
$authors[] = "PHP"; 
$authors[] = "CSS"; 
$authors[] = "HTML";  

Example 3

Add and change elements of associative arrays using square bracket syntax. Here an associative array is populated in two ways: first using the array() construct, and second using the square bracket syntax:

 
// Creating an associative array using the array() construct 
$myBook = array( "title" =>  "Learn PHP from java2s.com", 
                "author" =>  "java2s.com", 
                "pubYear" =>  2000 ); 
//from  www  .  j  ava 2 s  . c  o m
// Creating the same array using [] syntax 
$myBook = array(); 
$myBook["title"] = "Learn PHP from java2s.com"; 
$myBook["author"] = "java2s.com"; 
$myBook["pubYear"] = 2000;  

Changing elements of associative arrays works in a similar fashion to indexed arrays:

  
$myBook["title"] = "java from java2s.com"; 
$myBook["pubYear"] = 1952;  




















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone