Javascript is_array : Variable handling : PHP functions in JavaScript JAVASCRIPT TUTORIALS


JAVASCRIPT TUTORIALS » PHP functions in JavaScript » Variable handling »

 

Javascript is_array


Returns true if variable is an array
Example 1

Running
1.is_array(['Kevin', 'van', 'Zonneveld']);

Could return
1.true
Example 2

Running
1.is_array('Kevin van Zonneveld');

Could return
1.false
function is_array( mixed_var ) {
    // Returns true if variable is an array  
    // 
    // version: 901.1623
    // discuss at: http://phpjs.org/functions/is_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
    // +   bugfixed by: Manish
    // +   improved by: Onno Marsman
    // %        note 1: In php.js, javascript objects are like php associative arrays, thus JavaScript objects will also
    // %        note 1: return true
    // *     example 1: is_array(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: is_array('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 3: true
    // *     example 4: is_array(function tmp_a(){this.name = 'Kevin'});
    // *     returns 4: false
    var key = '';

    if (!mixed_var) {
        return false;
    }

    if (typeof mixed_var === 'object') {

        if (mixed_var.hasOwnProperty) {
            for (key in mixed_var) {
                // Checks whether the object has the specified property
                // if not, we figure it's not an object in the sense of a php-associative-array.
                if (false === mixed_var.hasOwnProperty(key)) {
                    return false;
                }
            }
        }

        // Uncomment to enable strict JavsScript-proof type checking
        // This will not support PHP associative arrays (JavaScript objects), however
        // Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
        //
        //  if (mixed_var.propertyIsEnumerable('length') || typeof mixed_var.length !== 'number') {
        //      return false;
        //  }

        return true;
    }

    return false;
}


HTML code for linking to this page:

Follow Navioo On Twitter

JAVASCRIPT TUTORIALS

 Navioo PHP functions in JavaScript
» Variable handling