Viewed   126 times

How do I get the current index in a foreach loop?

foreach ($arr as $key => $val)
{
    // How do I get the index?
    // How do I get the first element in an associative array?
}

 Answers

5

In your sample code, it would just be $key.

If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:

$i = -1;
foreach($arr as $val) {
  $i++;
  //$i is now the index.  if $i == 0, then this is the first element.
  ...
}

Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.

Tuesday, August 23, 2022
 
3

The reason for the "overwriting" is $tempChild = $child;.

That will not deep copy the contents of $child but make both $tempChild and $child point towards the same data structure, which obviously isn't desirable in this case.

You should use clone as in the below example.

$tempChild = clone $child;

  • PHP: Object Cloning - Manual
Saturday, November 12, 2022
 
jojodmo
 
5

Comments included.

<?php

//Require Core Component
require_once("xyz.php");

$Threads = new StackableArray();

//A Global Storage that will be shared between threads.
$Storage = new Storage();

//Store {count} in Global Storage
$Storage['count'] = 0;


/*
 * For Each Site, spawn a new thread, process the site and store result in Global Storage.
 */
foreach($sites as $site)
{
    $Thread = new SiteProcess($Storage, $site);
    $Thread->start();
    $Threads[$re] = $Thread;
}

//When the threads are complete, join them(destroy the threads)
foreach($Threads as $Thread)
{
    $Thread->join();
}

//A thread class
class SiteProcess extends Threads
{
    private $Storage;
    private $site;

    public function __construct(Storage $Storage, $site)
    {
        $this->Storage = $Storage;
        $this->site = $site;
    }

    public function run()
    {
        require_once("allsite/{$this->site}.php");
        $siteObj = new $this->site;
        $this->Storage[$this->Storage['count']] = $siteObj->getsiteData($query, $cat);
        $this->Storage['count'] = $this->Storage['count'] + 1;
    }
}

class StackableArray extends Stackable { public function run() { } };

class Storage extends Stackable { public function run() { } };
Wednesday, November 23, 2022
4

You can do something like this:

int i = 0;
foreach (var grouping in Class.Students.GroupBy(s => ++i / 20))
    Console.WriteLine("You belong to Group " + grouping.Key.ToString());
Sunday, November 27, 2022
 
5

In OS 3.x, there's a property called "zoomScale" that will give you what you want. In 2.x, I believe you can look directly at the contentView's transform to obtain this (but that is, of course, not 'official'.)

Tuesday, August 23, 2022
 
sunand
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :