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:
<?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 brackets, like this:
<?php $array["a"] = "Foo"; $array["b"] = "Bar"; $array["c"] = "Baz"; var_dump($array); ?>
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
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.