tags:

views:

66

answers:

3

This might be basic question but how do I create a list of lists in PHP. I would like to perform the following operations:

var x = List(List(1,1,1),List(2,2,2), List(3,3))
echo x[0]   //prints List(1,1,1)
echo x[1]   //prints List(2,2,2)
x  = x.List(4,4,4)
echo x      //prints List(List(1,1,1),List(2,2,2), List(3,3),List(4,4,4))
+3  A: 

You can make a list of lists using arrays.

$list1 = array(array('some stuff','more stuff'),array('more stuff2','some more'));

Or something like so:

$sub_list1=array('some stuff','more stuff');
$sub_list2=array('more stuff2','some more');
$list1 = array($sub_list1,$sub_list2);

You could access these lists like so:

echo $list1[0][1]; // Outputs "more stuff"
echo $list1[1][0]; // Outputs "more stuff2"
               ^ Select the element in that sub list
            ^ Select the sub list
Sam152
A: 
$ar=array(array("A","A1"),array("B","B1"))
$ar[]=array("C","C1"); // Append an item

print_r($ar[0]);  // debug purpose

$ar[]=$ar;

print_r($ar);
adatapost
+1  A: 

Lists are called "arrays" in PHP and they're pretty easy to work with:

You can instantiate one just by specifying its members:

$x = array(
    array(1, 1, 1),
    array(2, 2, 2),
    array(3, 3)
);

To append to an array, use empty square brackets:

$x[] = array(4, 4, 4);

To access a particular member, give its key in square brackets:

$x[0];  // array(1, 1, 1)

This works for multidimensional arrays too:

$x[0][2];  // 1

To print out an array so you can see the contents, use print_r or var_dump .. though print_r is neater for arrays.

echo $x;  // "Array" .. not great

print_r($x);
/* something like this:
array(
    0 => array (
        0 => 1
        1 => 1
        2 => 1
    )
    1 => array (
.. etc
*/

Arrays can also use strings as the key:

$x['foo'] = 'bar';

These are called "associative arrays".

nickf