Get next element in foreach loop

A unique approach would be to reverse the array and then loop. This will work for non-numerically indexed arrays as well: $items = array( ‘one’ => ‘two’, ‘two’ => ‘two’, ‘three’ => ‘three’ ); $backwards = array_reverse($items); $last_item = NULL; foreach ($backwards as $current_item) { if ($last_item === $current_item) { // they match } $last_item … Read more

PHP simple foreach loop with HTML [closed]

This will work although when embedding PHP in HTML it is better practice to use the following form: <table> <?php foreach($array as $key=>$value): ?> <tr> <td><?= $key; ?></td> </tr> <?php endforeach; ?> </table> You can find the doc for the alternative syntax on PHP.net

Check for null in foreach loop

Just as a slight cosmetic addition to Rune’s suggestion, you could create your own extension method: public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source) { return source ?? Enumerable.Empty<T>(); } Then you can write: foreach (var header in file.Headers.OrEmptyIfNull()) { } Change the name according to taste 🙂

Linq style “For Each” [duplicate]

Using the ToList() extension method is your best option: someValues.ToList().ForEach(x => list.Add(x + 1)); There is no extension method in the BCL that implements ForEach directly. Although there’s no extension method in the BCL that does this, there is still an option in the System namespace… if you add Reactive Extensions to your project: using … Read more

While destructuring an array, can the same element value be accessed more than once?

It looks pretty unorthodox and there will be very few scenarios when it is useful, but yes it is possible/valid. Just repeat the “key => value” syntax again and provide a different variable in the value position. In this context, the keys may be repeated. Here is a demonstration of using array destructuring to “pivot” … Read more

Timeout a function in PHP

It depends on your implementation. 99% of the functions in PHP are blocking. Meaning processing will not continue until the current function has completed. However, if the function contains a loop you can add in your own code to interrupt the loop after a certain condition has been met. Something like this: foreach ($array as … Read more

Possible to iterate backwards through a foreach?

If you are on .NET 3.5 you can do this: IEnumerable<int> enumerableThing = …; foreach (var x in enumerableThing.Reverse()) It isn’t very efficient as it has to basically go through the enumerator forwards putting everything on a stack then pops everything back out in reverse order. If you have a directly-indexable collection (e.g. IList) you … Read more