开发者

How to define single and multidimensional array in PHP?

I am beginner in PHP programming. I want to know how to define single and multidimensional开发者_StackOverflow社区 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. :-)


Array elements in PHP can hold values of any type, such as numbers, strings and objects. They can also hold other arrays, which means you can create multidimensional, or nested, arrays.

Single dimensional Array :

$myArray = array(value1, value2, value3); 

Multidimensional Array :

$myArray = array(
  array( value1, value2, value3 ),
  array( value4, value5, value6 ),
  array( value7, value8, value9 )
);  

Here, the top-level array contains 3 elements. Each element is itself an array containing 3 values.


Basically, there are three different types of arrays:

  1. Numeric array – An array with a numeric ID key.
  2. Multidimensional arrays – An array containing one or more arrays.
  3. Associative arrays – An array where each ID key is associated with a value.

Read here for more about these types : Types of Arrays in PHP


Did you read the manual ?

Especially the exemples, like this one :

$fruits = array ( "fruits"  => array ( "a" => "orange",
                                   "b" => "banana",
                                   "c" => "apple"
                                 ),
              "numbers" => array ( 1,
                                   2,
                                   3,
                                   4,
                                   5,
                                   6
                                 ),
              "holes"   => array (      "first",
                                   5 => "second",
                                        "third"
                                 )
            );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜