PHP Array Operator
In this chapter you will learn:
- What is PHP Array Operator
- Syntax for array operator []
- Example to use PHP Array Operator
- Example - Create Associative Arrays with Array Operator
Description
You can create and manage arrays using square brackets []
.
[]
can both create arrays and add elements to the end of an array.
Syntax
Array operator has the following syntax.
$arratName[] = "new Value";
or
$arratName[index] = "new Value";
or
$arratName["key"] = "new Value";
or
$arratName[index]; // get value by index
or
$arratName["key"]; // get value by key
Example 1
The following code uses the array operator to create and indexed array.
<?PHP/* j a v a 2 s . c o m*/
$array[] = "Foo";
$array[] = "Bar";
$array[] = "java2s.com";
var_dump($array);
?>
The code above generates the following result.
Example 2
For non-default indices, we can place our key inside the square brackets, like this:
<?PHP/*from j a v a 2s . c o m*/
$array["a"] = "Foo";
$array["b"] = "Bar";
$array["c"] = "Baz";
var_dump($array);
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- How to access array element
- Syntax to access array element
- Example - Access indexed array elements
- Example - Access elements from associative arrays
- Example - Put expression into array operator[]
Home » PHP Tutorial » PHP Array