Each function () and list ()

I do not understand well the functions of each () and list (). Can someone please give me a little more details and explain to me how this could be useful?

Edit:

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

So does this mean in the array [1] the value bob, but it is clearly located in the array [0]?

+3
source share
8 answers

list is not a function as such, since it is used in a completely different way.

Let's say you have an array

$arr = array('Hello', 'World');

With the help of listyou can quickly assign these different members of an array to variables

list($item1, $item2) = $arr; //$item1 equals 'Hello' and $item2 equals 'World'
+2
source

The each () function returns the current key and element value and moves the internal pointer forward. each ()

- , list()

  while(list($key,$val) = each($array))
    {
      echo "The Key is:$key \n";
      echo "The Value is:$val \n";

    }
+3

list CSV. , , CSV id, title text, :

1|Foo|Lorem ipsum dolor|
2|Bar|sit amet|
...

, , , list:

$lines = file( 'myFile.csv' );
for ( $i = 0; $i < count( $lines ); $i++ )
{
    list( $id, $title, $text, $null ) = explode( '|', $lines[$i], 4 );
    echo "Id: $id, Title: $title\n$text\n\n";
}

each - , , , . - foreach .

+2

: , , each

: PHP 7.2.0. ,


each(): ( $array[0 | "first value in association array ],

  $prices = ('x'=>100 , 'y'=>200 , 'z'= 300 );

, foreach.

while( $e = each($prices) ){
    echo $e[key] . "  " . $e[value] . "<br/>" ; 
}

, while . each(), . "" 0 , "" 1 .

, <

-, list(). "value" "key", each()

while( list($k , $v ) = each($prices) ){
    echo $k /*$e[key]*/  . "  " . $v /*$e[value]*/ . "<br/>" ;
    }

, each() , . list() , , .

: reset($prices):

each() .

+2

, . .

list($a, $b, $c) = array(1, 2, 3);

$a 1 ..

, . .

each , . , :

list($key, $val) = each($array);

RHS , $key $val. `$ array ' .

, :

while(list($key, $val) = each($array)):

, :

foreach($array as $key => $val): 
+1

:

, PHP / .

, , $bar[0] $bar[1]. , , $bar['key'] , $bar['value']. / , .

+1

, :

+---+------+-------+
|ID | Name | Job   |
| 1 | Al   | Cop   |
| 2 | Bob  | Cook  |
+---+------+-------+

- :

<?php
while(list($id,$name,$job) = each($array)) {
    echo "<a href=\"profile.php?id=".$id."\">".$name."</a> is a ".$job;
}
?>
+1

- , , , .

There are really no reasons at present for which I know that just use it instead foreach.

list()can be used separately from each()to assign array elements to more readable variables.

0
source

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


All Articles