Tag Archives: iterate

jQuery: How to Break Out of an Each Loop Programming 16 MAR 2015

The ever so useful jQuery javascript library has a homegrown loop function entitled .each(), which allows you to iterate over a jQuery object, and at the same time execute a function for each matched element.

Very useful indeed.

However, sometimes you might need to break out of a loop early (for example, maybe your loop has the potential of carrying on forever – which obviously is not so great for your patiently waiting audience) – and this is how you do it:

To break a $.each() loop, you have to return false in the loop callback function. (Returning true is equivalent to continue in a normal loop, in other words it skips to the next iteration – exactly the opposite of what you are trying to achieve!)

An example:

$(document).ready(function(){
$('.lotsOfTheseClassesExist').each(function(i, item){
alert($(item).prop('id'));
return false; //exits the loop
});
});

So your break statement for a jQuery each() loop is literally return false.

girl in pink high heels and a black leotard with lots and lots of shiny hula hoops

jquery logo

Related Link: http://api.jquery.com/each/

How to Apply a Function to Each Value in an Array CodeUnit 23 MAR 2010

Sometimes you wish to apply a certain function, be it a built in PHP function or one of your own creations, to each and every value within a particular array. Now doing this is of course as easy as writing a loop to iterate through an array, perform the function on each retrieved value and then save the updated value back into the array.

Easy, but unnecessary.

You see, PHP comes bundled with a great little function called array_map() that is used to apply a callback function to each and every value contained in the supplied array.

So for example if we wanted to throw strip_tags against an array’s contents, it would look something like this:

$original = array('

Paragraph

', 'Bold'); $new = array_map('strip_tags', $original);

As you would expect, the result of this would be an array containing the words Paragraph and Bold, devoid of all their HTML markup.

Nice!

Related Link: http://www.php.net/manual/en/function.array-map.php