PHP Array Operator

In this chapter you will learn:

  1. What is PHP Array Operator
  2. Syntax for array operator []
  3. Example to use PHP Array Operator
  4. 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:

  1. How to access array element
  2. Syntax to access array element
  3. Example - Access indexed array elements
  4. Example - Access elements from associative arrays
  5. Example - Put expression into array operator[]
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array