With PHP, is it possible to add list () to arrays?

I have a foreach loop that I am repeating. I try to have the variable β€œexplode” into parts and then be added to the corresponding arrays using list (), for example:

list($a[], $b[], $c[]) = explode(':', $loop); 

Can list () not do this? These are errors with

Fatal error: operator [] is not supported for strings

I suppose I could just use the temporary variables in the list () and then add them to the corresponding arrays later, for example:

 foreach($array as $loop) { list($a1, $b2, $c3) = explode(':', $loop); $a[] = $a1; $b[] = $b2; $c[] = $c3; } 

Is this a better or more efficient way to do this (e.g. fully using list ())?

+4
source share
2 answers

The list construct requires the correct expression of a variable, such as an array and index:

 foreach ($array as $i => $loop) { list($a[$i], $b[$i], $c[$i]) = explode(':', $loop); } 

Then everything works. Demo

Also, if these are really arrays, it works too:

 $a = $b = $c = array(); foreach ($array as $loop) { list($a[], $b[], $c[]) = explode(':', $loop); } 

Demo

+2
source

Yes you can .. Just add Index without initializing the variables

 list($a[0], $b[0], $c[0]) = explode(":","A:B:C") ; var_dump($a,$b,$c); 

Or Initialize Variables

 $a = $b = $c = array(); list($a[], $b[], $c[]) = explode(":","A:B:C") ; var_dump($a,$b,$c); 

Output

 array 0 => string 'A' (length=1) array 0 => string 'B' (length=1) array 0 => string 'C' (length=1) 
+1
source

Source: https://habr.com/ru/post/1439701/


All Articles