Thursday, 30 August 2018

How to define a single and multidimensional array in PHP?

I am beginner in PHP programming. I want to know how to define single and multidimensional array in PHP.


There are a wide variety of ways to do this, all of which are well explained on the relevant PHP manual page.
However, in terms of some examples:
$singleArray = array(1, 2, 3);

$multiArray = array(array(1, 2, 3), array(4, 5, 6));

You of course can also use the following syntax:
$singleArray = $multiArray = array();

$singleArray[] = 1;
$singleArray[] = 2;
...

$multiArray[0][] = "Bob";
$multiArray[0][] = "Steve";
$multiArray[1][] = "Dave";
$multiArray[1][] = "Jack";
...

You can also provide you own keys (in addition to the numeric ones), such as:
$singleArray = array('first'=>1, 'second'=>2, 'third'=>3);

(Use array_keys to extract the keys from such an array.)
However, if you're just starting out, you really want to spend a bit of time reading the excellent online documentation, practising with the tutorials, etc. as this will be a lot faster that asking a multitude of questions on SO. :-)

0 comments:

Post a Comment