php存储数组中的变量? [关闭]

I am just a newbie in php. So this question may be sound like childish. But I really want to know this.I saw in a php file one php code line was like this

$taxonomies = array();

Here it is looking like taxonomies is the variable stored in an array if I am not wrong. So can someone clear me what is the purpose of doing this?How the variable is stored in an array Any live example or any link will really clear my doubt.

This just defines that this variable is an array.

It declares $taxonomies as an empty array with no elements. You can use this to declare an array you don't know its element beforehand

$taxonomies = array(); 

echo count($taxonomies); //outputs 0 - meaning no elements

Start adding elements to the array

$taxonomies[] = "John";  //puts John in positon 0

$taxonomies['species'] = 'Pisces';  //associative array

$taxonomies[10] = 'Arachnida';

echo count($taxonomies); //outputs 3 - no longer empty

The variable $taxonomies does not become stored in the array after your example snippet, $taxonomies literally becomes an array.

array () is used to form an empty array, which is exactly what $taxonomies is after your statement.


To add elements to your new array you could either use the empty square-bracket trick ($taxonomies[] = "new element";) or array_push (among other functions).

As other people posted, it says the variable is array, which in turn will surpress warnings, when you will use $taxonomies forexample in foreach. Everytime when you can get an empty value out of some function etc and later you work with that variable as with an array, always do this check:

if(empty($taxonomies))$taxonomies = array();

Now you can write

foreach ($taxonomies as $value)

without having fear of PHP warnings

See http://php.net/manual/en/language.types.array.php

$taxonomies is set to a blank array

$taxonomies[0] = "foo" would set index 0 to foo

PHP also supports associative arrays so you could also do

$taxonomies["name"] = "John"

In PHP arrays are actually ordered maps, so you don't need to setup and initial size.