Reputation: 13
I have array like this: $test = array(20, 30, 40);
And I want to set a multi-dimension array with using these values: $example[20][30][40] = 'string'
How can I do this?
Note: "20, 30, 40" just an example, my program will print some integers, and I want to set a multi-dimension array with these values and it can be more than 3 values.
Upvotes: 1
Views: 127
Reputation: 11
<?php
$example = array();
$test = array(20, 30, 40);
foreach($test as $key=>$value)
{
$example[$value] = $test;
}
print_r($example);exit;
?>
Upvotes: 0
Reputation: 854
You could do it that way:
$example[$test[0]][$test[1]][$test[2]] = 'string'
Or if the size of the array is variable you will need to do a recursive function to fill up your array.
function fill_up($content, $value){
$index = array_shift($content);
if(count($content)){
return array($index => fill_up($content, $value));
} else {
return array($index => $value);
}
}
$example = array(20,30,40);
$value = 'test';
var_dump(fill_up($example, $value));
Upvotes: 1
Reputation: 8866
As 14moose seems to have been getting at, you can't make an empty array in PHP. It's not really an array. It's a map. You could certainly make a ridiculous multidimensional map using those input values, but that seems.. entirely useless.
Upvotes: 0
Reputation: 121881
Look here:
http://php.net/manual/en/language.types.array.php
EXAMPLE:
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar echo $arr[12]; // 1
EXPLANATION:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
This can be expanded to n-dimensions. It's equivalent to an array within an array:
2-D ARRAY EXAMPLE:
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42
'Hope that helps!
Upvotes: 0
Reputation: 141013
You can simply write :
$example[19][29][39] = 'string'
Do not forget that the first element is 0 and not 1. This should work.
Upvotes: 0