How to add elements to an array in PHP

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;
}




Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.