The array operator

There is another popular way to create and manage arrays, and it uses 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:

    $array[] = "Foo";
    $array[] = "Bar";
    $array[] = "Baz";

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 brackets, like this:

    $array["a"] = "Foo";
    $array["b"] = "Bar";
    $array["c"] = "Baz";


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Returning arrays from functions >>

Previous chapter: The two ways of iterating through arrays

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.