dvcolgan
dvcolgan

Reputation: 7728

PHP equivalent to Python's enumerate()?

In Python I can write:

for i, val in enumerate(lst):
    print i, val

The only way I know how to do this in PHP is:

for($i = 0; $i < count(lst); $i++){
    echo "$i $val\n";
}

Is there a cleaner way in PHP?

Upvotes: 19

Views: 12832

Answers (8)

kruk
kruk

Reputation: 85

I am using the helper function:

function enumerate(array &$array, callable $fn) {
    $i = 0;
    foreach ($array as $key => &$value)
        $fn($i++, $key, $value);
}

And I use it as follows:

enumerate($array, function ($i, $key, &$value) use (&$something)  {
    ...
});

The downside may be that you have to pass external variables that you want to use inside the loop through the use (...) directive.

Upvotes: 0

zekel
zekel

Reputation: 9467

If you want the index, key, and value, equivalent to this Python:

for ii, (key, value) in enumerate(my_dict.items()):
    print ii
    print key
    print value

You can create an enumerate function in PHP that wraps your objects. It's not meant to be efficient (it pre-iterates and collects everything) but it can be syntactically convenient.

function enumerate($array) {
    class IterObject {
        public $index;
        public $key;
        public $value;
    }

    $collect = array();
    $ii = 0;
    foreach ($array as $key => $value) {
        $iter = new IterObject();
        $iter->index = $ii;
        $iter->key = $key;
        $iter->value = $value;
        array_push($collect, $iter);
        $ii++;
    }
    return $collect;
}

Example usage:

foreach (enumerate($my_array) as $iter) {
    echo $iter->index;
    echo $iter->key;
    echo $iter->value;
}

Upvotes: 1

Wallace Vizerra
Wallace Vizerra

Reputation: 3541

In python enumerate has start argument, to define start value of enumeration.

My solution for this in php is:

function enumerate(array $array, $start = 0)
{
    $end = count($array) -1 + $start;

    return array_combine(range($start, $end), $array);
}

var_dump(enumerate(['a', 'b', 'c'], 6000));

The output is:

array(3) {
  [6000]=>
  string(1) "a"
  [6001]=>
  string(1) "b"
  [6002]=>
  string(1) "c"
}

Upvotes: 1

nemo
nemo

Reputation: 57739

With the introduction of closures in PHP 5.3 you can also write the following:

array_map(function($i,$e) { /* */ }, range(0, count($lst)-1), $lst);

Of course this only works if the array is stored in a variable.

Upvotes: 0

edam
edam

Reputation: 958

I think you were looking for the range function.

One use case could be the pagination where (assume) you have 150 items and you want to show 10 items per page so you have 15 links. So to create those links you can use:

    $curpage=3;$links=15;$perpage=10; //assuming.

    <?php foreach(range(1,$links) as $i):?>
        <?php if($i==$curpage):?>
             <li class="active"><a class="active"><?=$i?></a><li>
        <?php else:?>
             <li><a href="paging_url"><?=$i?></a><li>
        <?php endif ?>
    <?php endforeach ?>

Upvotes: 0

Tomasz Wysocki
Tomasz Wysocki

Reputation: 11568

Don't trust PHP arrays, they are like Python dicts. If you want safe code consider this:

<?php
$lst = array('a', 'b', 'c');

// Removed a value to prove that keys are preserved
unset($lst[1]);

// So this wont work
foreach ($lst as $i => $val) {
        echo "$i $val \n";
}

echo "\n";

// Use array_values to reset the keys instead
foreach (array_values($lst) as $i => $val) {
        echo "$i $val \n";
}
?>

-

0 a 
2 c 

0 a 
1 c 

Upvotes: 41

shamittomar
shamittomar

Reputation: 46692

Yes, you can use foreach loop of PHP:

 foreach($lst as $i => $val)
       echo $i.$val;

Upvotes: 0

Crozin
Crozin

Reputation: 44396

Use foreach:

foreach ($lst as $i => $val) {
    echo $i, $val;
}

Upvotes: 11

Related Questions