Hudzilla.org - the homepage of Paul Hudson
Contents > Arrays Wish List | Report Bug | About Me ]

5.4     The array operator

This is NOT the latest copy of this book; click here for the latest version.

There is another popular way to create an manage arrays, and it uses square brackets [ ] to mean "add to array", earning it the name "the array operator". Using this functionality, you can both create arrays and add to existing arrays, so this is generally more popular - you will generally only find the array() function being used when several values are being put inside the array, as it will fit on one line. Here are some examples of the array operator in action:

<?php
    $array
[] = "Foo";
    
$array[] = "Bar";
    
$array[] = "Baz";
    
var_dump($array);
?>

That should work in precisely the same as using the array() function, except it is much more flexible - we can add to the array whenever we want to. When it comes to working with non-default indices, we can just place our key inside the square brackets, like this:

<?php
    $array
["a"] = "Foo";
    
$array["b"] = "Bar";
    
$array["c"] = "Baz";
    
var_dump($array);
?>




<< 5.3 The three ways of iterating through arrays: list(), each(), and foreach loops   5.5 Returning arrays from functions >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
@$$@$$!N - 07 Sep 2008

The first line
" here is another popular way to create an manage arrays "
This is a mistake in the context . Instead of "and" you wrote "an"



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is eight plus six?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow