How to add elements to an array in PHP

- by

PHP-IconIt’s extremely easy to add elements to an existing array in PHP – so easy in fact that I regularly forget how to do it!

I’m used to initialising and setting up my variables from Objective C, but PHP is so much easier and deals with it on the fly. Here we do it – ideal for loops:

// create the array
$myArray = array();

// add three elements to it
$myArray[] = 'Hello';
$myArray[] = 'I must';
$myArray[] = 'be going';

// loop through all elements
foreach ($myArray as $item) {
  echo $item;
}


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.