We just show what we will feel is the mainstream way of each language to traverse an array. Alternative hacks can be added in the comments section.
Our goal here is to walk an array made of numbers and output their indexes in such fashion:
- 0 has 1
- 1 has 2
- 2 has 3
Another way to do it in PHP:
ReplyDeletereset($_array);
while(current($_array))
{
echo key($_array)," has ",current($_array);
next($_array);
}
also in PHP:
ReplyDeletefor( $i=0; $i<count($_array); $i++ )
echo $i,' has ',$_array[$i];
In JavaScript (ECMA only), you could also do:
ReplyDelete_array.forEach
(
function(item,key)
{
document.writeln(key+' has '+item)
}
)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
In JavaScript, you can also use jQuery:
ReplyDelete$.each(_array,function(index,item){
document.writeln(index+' has '+item) } )