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

Asked

Viewed 552 times

3

I got the following array

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

I’d like to use the function list to be able to capture some elements directly into variables, more or less like this:

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

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

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

I don’t want to have to do this:

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

  unset($id);

And if I wanted to skip two elements of array? would have to give unset in all first variables?

  • Next question, how to skip element 2 and 5 :D

2 answers

5


The option more is to assign the first element of the array to "nothing" or to define no variable.

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

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

In PHP5.x $nome will receive "Wallace" and $idade "26" however in PHP7 this behavior has been changed functioning in reverse form.

$array = [25, 'Wallace', '26 anos', 'linguagens' => ['PHP', 'Python', 'C#']];
list($nome, $idade) =  array_slice($array,1, 2);
  • Yes, little friend. But I thought you were going to put the other option, hehehehehe. + 1, good alternative

  • KKKKKKK, at the time I replied he updated, kkkkkkkk

  • @Wallacemaxters LOL was for about 30 seconds apart, I was looking for that other way that you spoke hehe.

  • Let me punch my answer to differentiate

  • @Guilhermenascimento can yes xD but the manual here is blocked I want to do a test on https://3v4l.org/ p shows the behavior in both versions, only it will be late afternoon'.

  • @Guilhermenascimento para php prefer that other link because it runs that code in almost all versions of php ai vc ve the difference in behavior. I do know :)

  • @Guilhermenascimento na documenta off line está assim "list() constructs can no longer be Empty. The following are no longer allowed" and one of the examples is list(,,) = $a;

  • @rray really I read wrong :/

Show 3 more comments

2

I’ve been looking forward to someone answering that one, but I’ve got to get a toothpick here.

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

That is, it is only necessary to do so:

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

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

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

There are still other more complex ways like:

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

Or else

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.