Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I skip array elements with `list` assignment?

Tags:

arrays

php

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:

  1. I use PHP 5.3 so construction like fruits()[2] will not work.

  2. I can do more assigns within one line of fairly readable code

  3. 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?

like image 299
Vlada Katlinskaya Avatar asked Feb 10 '23 12:02

Vlada Katlinskaya


2 Answers

php 5.5.14

function fruits(){
  $arr = array('apple','orange','banana','pear');
  return $arr;
}

list(,,$banana,$pear) = fruits();

echo $banana; // banana
like image 157
splash58 Avatar answered Feb 12 '23 02:02

splash58


Yes, you can skip elements: just omit the variable name:

list(,,$banana,$pear) = fruits();
like image 41
Alexander Guz Avatar answered Feb 12 '23 03:02

Alexander Guz