How can I "skip" elements of an array when I use "list"?

3

I have the following array

$array = [25, 'Wallace', '26 anos', 'linguagens' => ['PHP', 'Python', 'C#']

I would like to use the list function to capture some elements directly in variables, like this:

   list($id, $nome, $idade) = $array;

But I'd like to ignore the first element (which would be the $id variable), leaving only the following variables: $nome and $idade .

Is there any way to "skip" an element of array when creating variables with list ?

I do not want to have to do this:

   list($id, $nome, $idade) = $array;

  unset($id);

What if I wanted to skip 2 elements of array ? would you give unset on all the first variables?

    
asked by anonymous 13.05.2016 / 15:01

2 answers

5

The most option is to assign the first element of the array to "nothing", ie not defining any variable.

list(, $nome, $idade) = $array;

You can use array_slice() to extract the elements you want to use in list() , the second argument is from which element to start, and the third is the amount in case two in this example.

In PHP5.x $nome will receive "Wallace" and $idade "26" but in PHP7 this behavior was changed by working in reverse.

$array = [25, 'Wallace', '26 anos', 'linguagens' => ['PHP', 'Python', 'C#']];
list($nome, $idade) =  array_slice($array,1, 2);
    
13.05.2016 / 15:17
2

I was looking forward to someone answering this one, but I have to give a little one here.

The list in PHP natively supports "skipping" the listed elements simply by not declaring anything where a variable would normally be.

That is, you only need to do this:

  list(, $nome, $idade) = [15, 'Wallace', '26 anos'];

If you want to skip other elements, you can do this:

 list(,,$idade, $linguagens) = $array;

There are still other more complex ways like:

 list(,,$idade, list($php, $python)) = [15, 'Wallace', '25 anos', ['PHP', 'Python'])

Or

  list(,$nome,,$linguagens) = $array;
    
13.05.2016 / 15:48