Let's say I have a function returning the following array:
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
And I'd like to assign the third and forth array elements to a variables without using of temporary variable:
list(NULL,NULL,$banana,$pear) = fruits();
This code will not work, but it will show the idea of the way I'd like to use list
construction.
The reasons I'd like to use list
is the following:
I use PHP 5.3 so construction like fruits()[2]
will not work.
I can do more assigns within one line of fairly readable code
I'd like to skip temporary variables to reduce code size and increase its readability.
So is there any possibility to use list
and skip some array elements?
php 5.5.14
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
list(,,$banana,$pear) = fruits();
echo $banana; // banana
Yes, you can skip elements: just omit the variable name:
list(,,$banana,$pear) = fruits();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With