Long Ettinger
Long Ettinger

Reputation: 27

How to offset the start in a foreach loop?

I want my foreach starts of ex : $Element = 10 up to 20

At the moment :

foreach($lang['tech'] as $Element => $ElementName)
    {
       $parse['tt_name'] = $ElementName; // Displays the name

       if($Element > 99) // At over 99 foreach stop
       {
           break;  
       }
    }

I wish I had this principle in :

foreach($lang['tech'] as **$Element(10 to 20)** => $ElementName) // Display Element 10 to 20
    {
       $parse['tt_name'] = $ElementName; // Displays the name
    }

Thanks for your help

Upvotes: 0

Views: 1154

Answers (7)

Vadim Caen
Vadim Caen

Reputation: 1636

You can loop into the subarray :

foreach( array_slice ($yourarray , 10, 10) as $Element) {
...
} 

Upvotes: 0

splash58
splash58

Reputation: 26153

for($Element=10; $Element <=20; $Element++)
       {
       $parse['tt_name'] = $lang['tech'][$Element]; // Displays the name
    }

Upvotes: 0

miller
miller

Reputation: 934

You could use continue:

foreach($lang['tech' as $Element => $ElementName)
{
   if($Element < 10) // Less than 10 - skip!
   {
       continue;  
   }

   $parse['tt_name'] = $ElementName; // Displays the name

   if($Element > 99) // At over 99 foreach stop
   {
       break;  
   }
}

Or you could use for loop:

for ($Element=10; $Element<=99; $Element++) {
    $ElementName = $lang['tech'][$Element];
}

Upvotes: 1

jmattheis
jmattheis

Reputation: 11125

If i understand you correct you want to loop only element 10 to 20, you could use a for loop

for($i = 10; $i <= 20;$i++) {
    $entry = $lang['tech'][$i];
    // do something
}

Upvotes: 3

Mihai Matei
Mihai Matei

Reputation: 24276

You can filter it before iterating:

$tech = array_filter($lang['tech'], function($key) {
    return $key >= 10 && $key <= 20;
}, ARRAY_FILTER_USE_KEY);

foreach ($tech as $key => $name) {
    // do what you need
}

Upvotes: 0

099
099

Reputation: 333

You're missing ] in two places in your example code:

foreach($lang['tech'] as $Element => $ElementName)
                    ^

and

foreach($lang['tech'] as **$Element(10 to 20)** => $ElementName)
                    ^

Upvotes: 0

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

you missed ] in your foreach loop

foreach($lang['tech'] as $Element => $ElementName)
                    ^

Upvotes: 0

Related Questions