Wednesday, October 19, 2011

Traversing Arrays

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

In PHP

In JavaScript

In Bash

In ActionScript

In Perl

In Python

In Java

In Ruby

4 comments:

  1. Another way to do it in PHP:

    reset($_array);

    while(current($_array))
    {
    echo key($_array)," has ",current($_array);
    next($_array);
    }

    ReplyDelete
  2. also in PHP:

    for( $i=0; $i<count($_array); $i++ )
    echo $i,' has ',$_array[$i];

    ReplyDelete
  3. In JavaScript (ECMA only), you could also do:

    _array.forEach
    (
    function(item,key)
    {
    document.writeln(key+' has '+item)
    }
    )

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach

    ReplyDelete
  4. In JavaScript, you can also use jQuery:

    $.each(_array,function(index,item){
    document.writeln(index+' has '+item) } )

    ReplyDelete

Note: Only a member of this blog may post a comment.