Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

each() and list() function

Tags:

iterator

php

I don't understand the each() and the list() function that well. Can anyone please give me a little more detail and explain to me how can it 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 array[1] there's the value bob, but it's clearly in array[0]?

like image 386
Strawberry Avatar asked Feb 11 '10 23:02

Strawberry


3 Answers

list is not a function per se, as it is used quite differently.

Say you have an array

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

With list, you can quickly assign those different array members to variables

list($item1, $item2) = $arr; //$item1 equals 'Hello' and $item2 equals 'World'
like image 65
Tim Cooper Avatar answered Oct 06 '22 06:10

Tim Cooper


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

The list function — Assigns variables as if they were an array list()

Example usage is for iteration through arrays

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

    }
like image 21
streetparade Avatar answered Oct 06 '22 05:10

streetparade


A very common example for list is when thinking about CSV files. Imagine you have a simple database stored as CSV with the columns id, title and text, such a file could look like this:

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

Now when you parse this file you could do it like this, using the list function:

$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";
}

The other function, each, is basically just an old way to walk through arrays, using internal pointers. A more common way to do that is by using foreach now.

like image 41
poke Avatar answered Oct 06 '22 06:10

poke