PHP Create Array using Square Bracket
In this chapter you will learn:
- How to create array using square bracket
- Syntax to create array using square bracket
- Example - create array using square bracket
- Example - clear array first and then create array using square bracket
- Example - create associative 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 j ava 2 s. co 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;
Next chapter...
What you will learn in the next chapter:
- How to loop through PHP array
- Functions used to loop through array
- Example - Step through array
- Example - Retrieve the last element of the array without knowing how it's indexed
- Each function
- Example - Use each() to retrieve an array element with a value of false