<?php
$array['key1']['key2']=array();
array_push($array,$array['key1']=>'one',$array['key2']=>'two')
print_r($array['key1']['key2']);
?>

can someone tell me if this is possible for multidimensional arrays?
revise the code if I am wrong

actually I am creating a site for billboards reservation

Recommended Answers

All 10 Replies

It really isn't clear from the code you've posted what your starting array structure or desired finished array structure should be.

At a guess, you can do the following:

$array = array();
$array['key1'] = 'one';
$array['key2'] = 'two';

print_r($array);
/*
array(
    'key1' => 'one',
    'key2' => 'two',
)
*/

If that's incorrect, what exactly are you trying to achieve?

THe reason of this is I wanna try to add elements in a 2 dimensional array by assigning a key index then use array_push()

Array push can add a value (of any type) to an existing array.

array_push($array, $new_array);

If you want to assign values to a specific array index, you need to do it explicitly.
$array['my_index'] = $new_array;
Or
$array['my_index'][] = $new_array;

mr blocblue

does the blank square brackets is the container of the $new_array or not

Try just using:
$array['my_index'] = $new_array;

two ways of adding values to an array
by specific index (string|int)

$array = array();
$array['key1'] = $val1;
$array['key2'] = $val2;
print_r($array);
/*
array(
    "key1"=>$val1,
    "key2"=>$val2
)
echo array["key1"] // prints $val1
*/

adding values by "push" uses next available int

$array = array();
$array[] = $val1;
$array[] = $val2;
print_r($array);
/*
array(
    0=>val1,
    1=>val2
)
echo array[0] // prints $val1
*/

multidimensional array

$array = array();
$array[0][] = $val1;
$array[0][] = $val2;
$array[] = array($val3, $val4);
print_r($array);
/*
array(
    0=>array(
        0=>$val1
        1=>$val2
    ),
    1=>array(
        0=>$val3
        1=>$val4
    )
)
echo array[0] // prints $val1
*/

$array = array();
$array[0][] = $val1;
$array[0][] = $val2;
$array[] = array($val3, $val4);
print_r($array);

echo array[0] // prints $val1

<?php 
        $testing = array();

        for ($i=1; $i < 11 ; $i++) { 
            array_push($testing[$i] = $i);

            }
    ?> <pre><?php print_r($testing); ?></pre> 
Member Avatar for diafol

This thread has become totally unravelled. The precise intent (what type of keys) has not been made clear. Please can we stop posting here as it's becoming a dump for who-knows-what. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.