Example:
list($fruit1, $fruit2) = array('apples', 'oranges');
code above of course works ok, but code below:
list($fruit1, $fruit2) = array('fruit1' => 'apples', 'fruit2' => 'oranges');
gives: Notice: Undefined offset: 1 in....
Is there any way to refer to named keys somehow with list like list('fruit1' : $fruit1)
, have you seen anything like this planned for future release?
EDIT: This approach was useful back in the day (it was literally asked an answered over seven years ago), but see K-Gun's answer below for a better approach with newer PHP 7+ syntax.
Try the extract()
function. It will create variables of all your keys, assigned to their associated values:
extract(array('fruit1' => 'apples', 'fruit2' => 'oranges'));
var_dump($fruit1);
var_dump($fruit2);
With/from PHP 7.1;
$array = ['fruit1' => 'apple', 'fruit2' => 'orange'];
// [] style
['fruit1' => $fruit1, 'fruit2' => $fruit2] = $array;
// list() style
list('fruit1' => $fruit1, 'fruit2' => $fruit2) = $array;
print $fruit1; // apple
What about using array_values()?
<?php
list($fruit1, $fruit2) = array_values( array('fruit1'=>'apples','fruit2'=>'oranges') );
?>
If you are in my case:
list() only works on numerical array. So if you can, leaving blank in fetch() or fetchAll() -> let it have 2 options: numerical array and associative array. It will work.
It's pretty straightforward to implement.
function orderedValuesArray(array &$associativeArray, array $keys, $missingKeyDefault = null)
{
$result = [];
foreach ($keys as &$key) {
if (!array_key_exists($key, $associativeArray)) {
$result[] = $missingKeyDefault;
} else {
$result[] = $associativeArray[$key];
}
}
return $result;
}
$arr = [
'a' => 1,
'b' => 2,
'c' => 3
];
list($a, $b, $c) = orderedValuesArray($arr, ['a','AAA', 'c', 'b']);
echo $a, ', ', $b, ', ', $c, PHP_EOL;
output: 1, , 3
- less typing on usage side
- no elements order dependency (unlike
array_values
)
- direct control over variables names (unlike
extract
) - smaller name collision risk, better IDE support
consider this an elegant solution:
<?php
$fruits = array('fruit1'=> 'apples','fruit2'=>'oranges');
foreach ($fruits as $key => $value)
{
$$key = $value;
}
echo $fruit1; //=apples
?>
<?php
function array_list($array)
{
foreach($array as $key => $value)
$GLOBALS[$key] = $value;
}
$array = array('fruit2'=>'apples','fruit1'=>'oranges');
array_list($array);
echo $fruit1; // oranges
?>