Looping through array and output as pairs (divider for each second element)

arrays, foreach, javascript, jquery

Solution

Well, maybe this is the most basic solution:

for (var i = 0; i < arr.length; i += 2) {
    var title = arr[i];
    var len = arr[i+1];
}

However, I would recommend you to arrange `$playlist` as follows:

while (databaseloop) {
    $playlist[] = array(
        "title" => $a_title,
        "length" => $a_length
    );
}

Then it will be easy to iterate the elements simply with:

for (var i = 0; i < arr.length; i++) {
    var title = arr[i]['title'];
    var len = arr[i]['length'];
}

Problem

I have an array with anonymous elements. Elements are added to the array via php, like so: ``` $playlist = array(); while (databaseloop) { $playlist[] = $a_title; $playlist[] = $a_length; } echo json_encode(array('playlist'=>$playlist)); ``` So the array becomes: ``` ["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"] and so on ``` Then I retrieve this array in jquery with ajax post. All that works fine. Now, I'm looking for a way to treat/output all array elements as pairs in javascript/jquery. "do something" for each second element. Like this: ``` foreach (two_elements_in_array) { // output track name // output track time // output some divider } ``` How can this be done?

Original source