» Javascript equivalent for PHP's is_array

399 PHP equivalents

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: is_array.

I have moved out PHP.JS to it's own site. For info & reactions on comments please goto phpjs.org

PHP is_array

Description

is_array - Finds whether a variable is an array

bool is_array ( mixed var)

Finds whether the given variable is an array.

Parameters

  • var

    The variable being evaluated.

Return Values

Returns TRUE if var is an array, FALSE otherwise.

See Also

Javascript is_array

Source

This is the main source of the Javascript version of PHP's is_array

function is_array( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
    // +   bugfixed by: Manish
    // +   improved by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: In php.js, javascript objects are like php associative arrays, thus JavaScript objects will also
    // %        note 1: return true  in this function (except for objects which inherit properties, being thus used as objects),
    // %        note 1: unless you do ini_set('phpjs.objectsAsArrays', true), in which case only genuine JavaScript arrays
    // %        note 1: will 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 = '';
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if(!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
 
    if (!mixed_var) {
        return false;
    }
 
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
 
    if (typeof mixed_var === 'object') {
 
        if (this.php_js.ini['phpjs.objectsAsArrays'] &&  // Strict checking for being a JavaScript array (only check this way if call ini_set('phpjs.objectsAsArrays', 0) to disallow objects as arrays)
            (
            (this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase &&
                    this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase() === 'off') ||
                parseInt(this.php_js.ini['phpjs.objectsAsArrays'].local_value, 10) === 0)
            ) {
            return mixed_var.hasOwnProperty('length') && // Not non-enumerable because of being on parent class
                            !mixed_var.propertyIsEnumerable('length') && // Since is own property, if not enumerable, it must be a built-in function
                                getFuncName(mixed_var.constructor) !== 'String'; // exclude String()
        }
 
        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;
                }
            }
        }
 
        // Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
        return true;
    }
 
    return false;
}

Examples

Currently there are 4 examples

Example 1

This is how you could call is_array()
is_array(['Kevin', 'van', 'Zonneveld']);
And that would return
true

Example 2

This is how you could call is_array()
is_array('Kevin van Zonneveld');
And that would return
false

Example 3

This is how you could call is_array()
is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
And that would return
true

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalBrett Zamir (link) for contributing to:
 array_diff, array_diff_assoc, array_diff_key, array_diff_uassoc, array_diff_ukey, array_fill_keys, array_fill_keys, array_filter, array_intersect, array_intersect_assoc, array_intersect_key, array_intersect_uassoc, array_intersect_ukey, array_keys, array_map, array_merge, array_merge_recursive, array_pop, array_search, array_slice, array_slice, array_splice, array_udiff, array_udiff_assoc, array_udiff_uassoc, array_uintersect, array_uintersect_assoc, array_uintersect_uassoc, array_unique, arsort, arsort, asort, asort, compact, current, each, end, extract, key, krsort, ksort, natcasesort, natcasesort, natsort, natsort, next, pos, prev, reset, rsort, rsort, shuffle, sort, sort, uasort, uasort, uksort, usort, classkit_import, classkit_method_add, classkit_method_copy, classkit_method_redefine, classkit_method_remove, classkit_method_rename, class_exists, get_class_methods, get_class_vars, get_declared_classes, get_object_vars, method_exists, property_exists, ctype_alnum, ctype_alpha, ctype_cntrl, ctype_digit, ctype_graph, ctype_lower, ctype_print, ctype_punct, ctype_space, ctype_upper, ctype_xdigit, date, date, date, date, date_default_timezone_get, date_default_timezone_set, date_parse, gettimeofday, gmdate, gmmktime, gmstrftime, idate, localtime, mktime, strftime, strtotime, timezone_abbreviations_list, timezone_identifiers_list, restore_exception_handler, set_exception_handler, fclose, feof, fgetc, fgetcsv, fgets, fgetss, filemtime, fopen, fpassthru, fread, fseek, ftell, pathinfo, pclose, popen, readfile, rewind, call_user_func, call_user_func_array, create_function, func_get_arg, func_get_args, func_num_args, get_defined_functions, get_defined_functions, register_shutdown_function, assert, assert_options, get_cfg_var, get_defined_constants, get_required_files, getenv, getlastmod, ini_alter, ini_get, ini_get_all, ini_restore, ini_set, php_ini_loaded_file, php_ini_scanned_files, phpversion, putenv, set_time_limit, include, include_once, require, require_once, atan2, expm1, fmod, log1p, rand, constant, define, defined, die, exit, exit, php_strip_whitespace, sleep, time_nanosleep, time_sleep_until, usleep, gopher_parsedir, setrawcookie, aggregate, aggregate_info, aggregate_methods, aggregate_methods_by_list, aggregate_methods_by_regexp, aggregate_properties, aggregate_properties_by_list, aggregate_properties_by_regexp, aggregation_info, deaggregate, preg_grep, sql_regcase, runkit_class_adopt, runkit_class_emancipate, runkit_function_add, runkit_function_copy, runkit_function_redefine, runkit_function_remove, runkit_function_rename, runkit_import, runkit_method_add, runkit_method_copy, runkit_method_redefine, runkit_method_remove, runkit_method_rename, runkit_superglobals, chunk_split, convert_uuencode, count_chars, echo, get_html_translation_table, lcfirst, levenshtein, localeconv, md5, md5_file, nl2br, nl_langinfo, parse_str, printf, quoted_printable_decode, quoted_printable_decode, quoted_printable_encode, setlocale, sha1, soundex, sprintf, str_getcsv, str_ireplace, str_replace, str_replace, str_shuffle, str_split, str_word_count, strcoll, strcspn, strip_tags, strlen, strnatcasecmp, strncmp, strrchr, strspn, strtok, strtr, substr_compare, substr_replace, ucfirst, vprintf, base64_decode, get_headers, get_meta_tags, parse_url, rawurldecode, rawurldecode, rawurlencode, rawurlencode, rawurlencode, urldecode, urldecode, urlencode, urlencode, doubleval, get_defined_vars, get_resource_type, gettype, import_request_variables, import_request_variables, is_array, is_array, is_binary, is_buffer, is_callable, is_real, is_resource, is_unicode, print_r, print_r, settype, strval, strval, unserialize, var_dump, var_export, utf8_decode
spacemedalOnno Marsman for contributing to:
 acos, acosh, asin, asinh, atan, atanh, ceil, cos, cosh, decbin, dechex, decoct, exp, floor, fmod, getrandmax, hypot, is_finite, is_infinite, is_nan, lcg_value, log, log10, max, max, min, min, mt_getrandmax, mt_rand, pi, pow, rand, round, sin, sinh, sqrt, tan, tanh, setcookie, preg_quote, addslashes, bin2hex, count_chars, html_entity_decode, htmlentities, htmlspecialchars_decode, levenshtein, ltrim, nl2br, nl2br, ord, parse_str, rtrim, soundex, str_ireplace, str_replace, str_replace, str_rot13, str_split, strcasecmp, strip_tags, stripos, stripslashes, stristr, strlen, strnatcmp, strncasecmp, strpbrk, strpos, strrev, strripos, strrpos, strstr, strtolower, strtoupper, substr, substr_count, trim, ucfirst, ucwords, base64_decode, empty, empty, is_array, is_bool, isset, utf8_decode, utf8_encode, utf8_encode
spacemedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, vprintf, http_build_query, floatval, is_object, print_r
spacemedalWaldo Malqui Silva for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, strncmp, ucwords, settype
spacemedalPaulo Ricardo F. Santos for contributing to:
 getdate, microtime, constant, define, chop, chunk_split, quotemeta, sprintf, get_headers, gettype, is_double, is_float, is_integer, is_long, is_scalar
spacemedalJack for contributing to:
 compact, max, min, count_chars, htmlentities, md5, parse_str, soundex, sprintf, str_ireplace, strnatcmp, trim, utf8_encode
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalPhilip Peterson for contributing to:
 sizeof, log10, round, exit, echo, get_html_translation_table, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, each, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalMartijn Wieringa for contributing to:
 array_shift, array_unshift, str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalNate for contributing to:
 array_merge, array_sum, array_unique, pathinfo, addslashes, echo, strncasecmp
spacemedalEnrique Gonzalez for contributing to:
 file_exists, filesize, decbin, decoct, deg2rad, rad2deg
spacemedalPhilippe Baumann for contributing to:
 base_convert, bindec, dechex, hexdec, octdec, empty
spacemedalTheriault for contributing to:
 array_multisort, quoted_printable_decode, quoted_printable_decode, quoted_printable_encode, quoted_printable_encode
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf, vprintf
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalJani Hartikainen for contributing to:
 file, file_exists, file_get_contents, filesize
spacemedalOle Vrijenhoek for contributing to:
 convert_uuencode, convert_uuencode, quoted_printable_decode, str_word_count
spacemedaltravc for contributing to:
 rawurldecode, rawurlencode, urldecode, urlencode
spacemedalAlex for contributing to:
 get_html_translation_table, strip_tags, is_int
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map, define, levenshtein
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalGeekFG (link) for contributing to:
 krsort, ksort, time
spacemedalJohnny Mast (link) for contributing to:
 array_walk, array_walk_recursive, create_function
spacemedalMichael Grier for contributing to:
 array_unique, wordwrap, rawurlencode
spacemedald3x for contributing to:
 array, explode, unserialize
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalstag019 for contributing to:
 parse_str, parse_str, http_build_query
spacemedalAJ for contributing to:
 urldecode, urlencode
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalBreaking Par Consulting Inc (link) for contributing to:
 gettimeofday, localtime
spacemedalCaio Ariede (link) for contributing to:
 strtotime, strtotime
spacemedalDavid for contributing to:
 strtotime, is_numeric
spacemedalJosh Fraser (link) for contributing to:
 gettimeofday, localtime
spacemedalKELAN for contributing to:
 get_html_translation_table, gettype
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalLars Fischer for contributing to:
 urldecode, urlencode
spacemedalMarc Palau for contributing to:
 mktime, strip_tags
spacemedalMirek Slugen for contributing to:
 htmlspecialchars, htmlspecialchars_decode
spacemedalOleg Eremeev for contributing to:
 str_replace, str_replace
spacemedalPellentesque Malesuada for contributing to:
 base64_decode, base64_encode
spacemedalPublic Domain (link) for contributing to:
 json_decode, json_encode
spacemedalSakimori for contributing to:
 strlen, wordwrap
spacemedalSteve Hilder for contributing to:
 strcmp, strncmp
spacemedalSteven Levithan (link) for contributing to:
 trim, parse_url
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalgettimeofday for contributing to:
 date, idate
spacemedalgorthaur for contributing to:
 strcmp, strncmp
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedal0m3r for contributing to:
 array_diff_assoc
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndreas for contributing to:
 setcookie
spacemedalAndrej Pavlovic for contributing to:
 serialize
spacemedalAnton Ongson for contributing to:
 str_replace
spacemedalArno for contributing to:
 htmlspecialchars
spacemedalAtli Þór for contributing to:
 nl2br
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBen Bryan for contributing to:
 print_r
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBlues (link) for contributing to:
 strftime
spacemedalBlues at link for contributing to:
 setlocale
spacemedalBobby Drake for contributing to:
 strip_tags
spacemedalBrad Touesnard for contributing to:
 date
spacemedalBryan Elliott for contributing to:
 date
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalChaosNo1 for contributing to:
 timezone_abbreviations_list
spacemedalChristian Doebler for contributing to:
 sleep
spacemedalCord for contributing to:
 is_array
spacemedalDaniel Esteban for contributing to:
 strpos
spacemedalDavid James for contributing to:
 get_class
spacemedalDavid Randall for contributing to:
 date
spacemedalDer Simon (link) for contributing to:
 echo
spacemedalDino for contributing to:
 serialize
spacemedalDiogo Resende for contributing to:
 number_format
spacemedalDouglas Crockford (link) for contributing to:
 gettype
spacemedalDxGx for contributing to:
 trim
spacemedalEric Nagel for contributing to:
 strip_tags
spacemedalEugene Bulkin (link) for contributing to:
 echo
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFrancesco for contributing to:
 empty
spacemedalFrancois for contributing to:
 htmlspecialchars_decode
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalGaragoth for contributing to:
 serialize
spacemedalGilbert for contributing to:
 array_sum
spacemedalHoward Yeend for contributing to:
 number_format
spacemedalHyam Singer (link) for contributing to:
 exit
spacemedalJ A R for contributing to:
 end
spacemedalJalal Berrami for contributing to:
 import_request_variables
spacemedalKirk Strobeck for contributing to:
 strlen
spacemedalKristof Coomans (SCK-CEN (Belgian Nucleair Research Centre)) for contributing to:
 strnatcasecmp
spacemedalLH for contributing to:
 empty
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalLinuxworld for contributing to:
 bin2hex
spacemedalLuke Godfrey for contributing to:
 strip_tags
spacemedalLuke Smith (link) for contributing to:
 number_format
spacemedalManish for contributing to:
 is_array
spacemedalMarc Jansen for contributing to:
 empty
spacemedalMarco for contributing to:
 get_html_translation_table
spacemedalMartin Pool for contributing to:
 strnatcasecmp
spacemedalMateusz "loonquawl" Zalega for contributing to:
 htmlspecialchars_decode
spacemedalMatt Bradley for contributing to:
 is_int
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNathan for contributing to:
 htmlspecialchars
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalNorman "zEh" Fuchs for contributing to:
 utf8_decode
spacemedalOle Vrijenhoek (link) for contributing to:
 filemtime
spacemedalOzh for contributing to:
 dirname
spacemedalPaul for contributing to:
 exit
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPierre-Luc Paour for contributing to:
 strnatcasecmp
spacemedalPul for contributing to:
 strip_tags
spacemedalPyerre for contributing to:
 checkdate
spacemedalReverseSyntax for contributing to:
 htmlspecialchars_decode
spacemedalRival for contributing to:
 number_format
spacemedalRobin for contributing to:
 is_nan
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSaulo Vallory for contributing to:
 strncasecmp
spacemedalScott Cariss for contributing to:
 htmlspecialchars_decode
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSlawomir Kaniecki for contributing to:
 htmlspecialchars_decode
spacemedalSoren Hansen for contributing to:
 count
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSubhasis Deb for contributing to:
 array_merge_recursive
spacemedalT. Wild for contributing to:
 filesize
spacemedalT.Wild for contributing to:
 substr
spacemedalT0bsn for contributing to:
 crc32
spacemedalThiago Mata (link) for contributing to:
 call_user_func_array
spacemedalTim Wiel for contributing to:
 date
spacemedalTim de Koning for contributing to:
 is_numeric
spacemedalTod Gentille for contributing to:
 log10
spacemedalValentina De Rosa for contributing to:
 strspn
spacemedalVictor for contributing to:
 ip2long
spacemedalWagner B. Soares for contributing to:
 strtotime
spacemedalXoraX (link) for contributing to:
 dirname
spacemedalYUI Library: link for contributing to:
 setlocale
spacemedalYannoo for contributing to:
 mktime
spacemedalYves Sucaet for contributing to:
 utf8_encode
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedalclass_exists for contributing to:
 get_declared_classes
spacemedaldate for contributing to:
 idate
spacemedaldjmix for contributing to:
 basename
spacemedaldptr1988 for contributing to:
 unserialize
spacemedalduncan for contributing to:
 array_unique
spacemedalecho is bad for contributing to:
 echo
spacemedalejsanders for contributing to:
 vsprintf
spacemedalgabriel paderni for contributing to:
 mktime
spacemedalger for contributing to:
 html_entity_decode
spacemedalhitwork for contributing to:
 utf8_decode
spacemedaljakes for contributing to:
 mktime
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedaljohnrembo for contributing to:
 var_export
spacemedalkenneth for contributing to:
 explode
spacemedalmadipta for contributing to:
 get_html_translation_table
spacemedalmarc andreu for contributing to:
 html_entity_decode
spacemedalmetjay for contributing to:
 time
spacemedalmk.keck for contributing to:
 realpath
spacemedalmktime for contributing to:
 gmmktime
spacemedalnobbler for contributing to:
 htmlentities
spacemedalnoname for contributing to:
 get_html_translation_table
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
spacemedalrezna for contributing to:
 stripslashes
spacemedalsankai for contributing to:
 array_count_values
spacemedalsetcookie for contributing to:
 setrawcookie
spacemedalsowberry for contributing to:
 utf8_encode
spacemedalstensi for contributing to:
 intval
spacemedalstrcasecmp, strcmp for contributing to:
 substr_compare
spacemedaltaith for contributing to:
 is_numeric
spacemedaluestla for contributing to:
 strtr

Your name here?

Contributing is as easy as adding a comment with better code, or code for a new function.
Any contribution leading to improvement will directly get your name & link here.


Coming Project features

Project features that we are currently working on:

  • Done - Site. A place for php.js of it's own. See: phpjs.org.
  • Done - Compile. Compile your own php.js version, with only the functions you need. Should generate a hash with which you can retrieve latest versions of your php.js combination.
  • Done - Testsuite. A better test-suite that can be ran locally so developers can easily test before commiting. Also the testing itself should be more thorough.
  • Done - Versioning. Individual functions are versioned, but the entire library should be versioned as well.

Stay up to date

You can track my blog rss articles and rss comments. You may also find my rss bookmarks interesting. Or twitter Follow me on Twitter


Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, php, javascript
category: Programming - Javascript - PHP equivalents
read: 18,015 times

Add Comment

PHP.JS is outgroing this blog and moving to it's own space. Please leave your comment here: http://phpjs.org/functions/is_array

Comments

#42. Kevin on 16 March 2009

Member avatar: Kevin@ mk.keck: I will review your comment soon over at http://phpjs.org . Please bear with me, and use that new site for comments on PHP.JS from now on.

Thanks a lot!!

#41. mk.keck on 06 March 2009

Gravatar.com: mk.keckImproved function is_array():
Why not let the user change dynamicly the behavior of is_array()?

function is_array() {
var a = arguments;
if (a.length < 1) {
return false;
}
// Check Value
var v = a[0];
// Check Strict
var s = ( (typeof(a[1]) !== 'undefined' && a[1]) ? 1 : 0 );
if (typeof(v) === 'object') {
if (v.hasOwnProperty) {
for (var k in v) {
// 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 === v.hasOwnProperty(k)) {
return false;
}
}
}
// If (s > 0) then strict JavsScript-proof type checking
// is enabled. 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 (s > 0) {
if (v.propertyIsEnumerable('length') || typeof(v.length) !== 'number') {
return false;
}
}
return true;
}
return false;
}

#40. Brett Zamir on 10 February 2009

Gravatar.com: Brett ZamirHere's my stab at isArray() (I'm not using the PHP format since this doesn't return true for objects/associative arrays) in case any were interested.

function isArray (arr) {
if (arr instanceof Array || // catch most common occurrence and exist quickly if so
(
... [more] 'splice' in arr.constructor.prototype &&
'concat' in arr.constructor.prototype && // not a word, so may be safer than splice, but can't replace it since concat present on string object
!(arr.propertyIsEnumerable('length')) &&
typeof arr.length === 'number'
)
) {
return true;
}
return false;
}

#39. Brett Zamir on 27 January 2009

Gravatar.com: Brett ZamirHi Luke,

Yes, thanks for pointing it out. But also note "Martin B." makes the same observation I did per the "Miller device" on the blog you cite. There's apparently really no foolproof/secure way to conclusively determine something is an array (and only an array) in JS.

#38. Luke on 26 January 2009

Gravatar.com: Luke@Brett, FYI, Doug uses the Object.proto.toString method now.

http://blog.360.yahoo.com/blog-TBPekxc1dLNy5DOloPfzVvFIVOWMB0li?p=916

#37. Kevin on 25 January 2009

Member avatar: Kevin@ Luke: Thanks for the heads-up. Interesting article. But for the record: it's not exactly our philosophy to obfuscate object types. I don't even think there is a WE in this matter.

But my view is: that if you're 'inside' php.js, you have a PHP mindset and expect associative arrays to be, well, just arrays.

You'd probably want this to just execute:

var keys = array('0', '1', '2');
var vals = array('a', 'b', 'c');
 
combined = array_combine(keys, vals);
if (is_array(combined)) { // WILL FAIL IF WE DENY OBJECTS!
print_r(combined);
}


.. but it clearly doesn't if we don't allow objects to be arrays as well.. And so we've been struggling with imperfection since.

Luckily, if you need the JavaScript-point-of-view of a variable, you can also just use JavaScript code to establish that. If you want the php point-of-view, use php.js functions.

#36. Brett Zamir on 25 January 2009

Gravatar.com: Brett ZamirHi Luke,
Clever idea--I like it. Of course it's not foolproof if somebody overrides the Object prototype's toString() (e.g., to list all of its properties). I think an even more robust solution (and one unlikely to fail in an environment which played with built-in prototypes) might simply be to build on Crockford's approach and test for further methods (e.g., 'concat' is a pretty unlikely property) and/or to insist the method is on the prototype (excluding a user from having the property as a direct property). For example, the test, ('concat' in obj.constructor.prototype ), would catch arrays but not even {concat:'something'}. Someone could still do "delete Array.prototype.splice" but I think that would be much less likely than overriding Object.prototype.toString() which has some potential uses.

#35. Luke on 24 January 2009

Gravatar.com: LukeWhile I entirely disagree with the philosophy of obfuscating a purposeful distinction in object types vis Array vs Object in the language you are entreating your consumers to write in, it has recently become best practice in js to check for Array type using this technique:

function isArray(a) {
return Object.prototype.toString.call(a) === '[object Array]';
}


See this article for reference:
http://thinkweb2.com/projects/prototype/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/

#34. Onno Marsman on 20 January 2009

Gravatar.com: Onno MarsmanHadn't looked at this 'thread' for a while and I see there's still a question from Brett more or less open for me, about the hasOwnProperty solution and the answer to that is pretty much the same as my feelings for the whole framework/configuration idea:

I only use phpjs for the functions that are missing from javascript, and I also use it to promote javascript for other php-developers in my team because they can easily see in this library how some things can be done in javascript. About everything beyond that: I really don't care what happens: as long as I have simple functions that I can copy/paste and there aren't a lot of dependencies (which includes configuration for these functions I guess). The functions I'm talking about don't include is_array or exit or stuff like that, but I guess I've been clear on that.

#33. Kevin on 15 January 2009

Member avatar: Kevin@ Brett Zamir: It would be cool to see other implementations coming to live. As long as I can focus on a simple robust base, people will have something consistent to build their spinoffs on.

So like I said: Personally I would like to focus on the main php.js library. Still a lot of work to be done there.

But I encourage anyone who takes that and puts it to other use. Even you :)

#32. Brett Zamir on 14 January 2009

Gravatar.com: Brett ZamirHi Kevin and Onno,

My feeling is that it's a toss-up. It doesn't bother me though because I really feel that after implementing more of the functions, it will be good to make a customizable version (on my own if you're not interested), since different people may want to handle things differently.

It's not like people can't study a little bit to set up something as potentially useful as this (and they should know what the code is doing before relying on it). A few main global configuration options (though ideally over-rideable on a function-by-function or function-group basis) like
... [more]
1) When if at all to treat objects as associative arrays

2) Whether to follow PHP strictly or enable some useful customizations (not too many, but a few
that are just too natural/useful to pass up); basically the things in the functions which told people that they could uncomment the given lines (or the ones we wanted to add but felt would deviate too much from PHP--e.g., a file_get_contents() that could be configured to work with asynchronous Ajax, with Firefox (or possibly Explorer) local file access code, etc.)

#31. Kevin on 14 January 2009

Member avatar: Kevin@ Onno Marsman & Brett Zamir:

What if we traverse the variable and verify that hasOwnProperty returns true for every element, and only then return true for is_array?

That way you can be pretty sure that this object is just a storage container, and nothing fancy otherwise.

#30. Kevin on 31 December 2008

Member avatar: Kevin@ Onno Marsman: You are totally right. How about the current comment.

@ Brett Zamir: I didn't even know that, I'm amazed actually. Google's got some work to do on improving her engine :)

About the frameworks: Besides the obvious naming conflicts, the main reason I created the namespaced version was for others to be able to more easily extend & build on top of it.

#29. Onno Marsman on 30 December 2008

Gravatar.com: Onno MarsmanOk, than we'll just leave it to return true on objects.


I do have a tiny little problem (I just can't help myself, sorry) with the comments: "Uncomment to disable support" It's not that it's not supported if you do that, it just behaves differently with all the pros en cons we discussed. If you do feel that it would be disabling support for ..., it wouldn't make any sense to put it there: who would want to disable support for something?

#28. Brett Zamir on 30 December 2008

Gravatar.com: Brett ZamirWell, it's sure a good sign that people are interested in your project, if it's the third item on Google showing up for "PHP is_array" (after the PHP site and a mirror). Congratulations, wow! And that's without "JavaScript" even in the query (its the first with that one).

I think that's entirely reasonable to avoid the configuration, though I think it could be interesting to integrate it into a separate framework. Heck, maybe I might try something with it later on because I do think it could be very useful.

#27. Kevin on 30 December 2008

Member avatar: Kevin@ Onno marsman, T. Wild, Brett Zamir: Thanks your insightful comments. Appreciated.

-- PHP.JS: Brett you have laid out what the project is about, and a couple of your paragraphs should probably make it to the phpjs.org site. Thanks. But in this particular case, you're preaching to the choir ;) We have all invested our precious free time in this project, because we are already convinced of it's purpose (and as it turns out, even more people see even more purposes for it, I have even heard people are trying to bring our PHP power to Adobe AIR ;)

-- Configurable PHP.JS:
My vision on the project: I think we should Not try to create a Framework. Let us stick with creating a Library. Others are invited to take our (namespaced / compiled) Library and extend it in whatever way they see fit, we should focus on delivering raw PHP power, as close to the original PHP as reasonably possible. This goal should not provide the need for configuration.

If it's even possible to have a setup file for a library (and still call it that), it would over-complicate & potentially make things unstable. I side with Onno on that one. Besides: there's lower hanging fruit still to be plucked.

-- InstanceOf:
T.Wild thanks for your url http://javascript.crockford.com/remedial.html . In these ways, working on PHP.JS has helped me to get a better understanding of both languages. That's very cool. I've changed the gettype function to fix the type problems stated in your find. I also implemented (& commented) it in the is_array function.

-- is_array:
We once made the decision that PHP.JS should accept associative arrays. I still think we can not make an exception now. Having said we should mimic PHP as much as reasonably possible, I would very much like this code:

var combined;
var keys = ['0', '1', '2'];
var vals = ['a', 'b', 'c'];
 
combined = array_combine(keys, vals);
if (is_array(combined)) {
print_r(combined);
}

to produce:
Array
(
[0] => a
[1] => b
[2] => c
)

And not ''. I realize that it's choosing between two evils. Maybe it's because I'd rather look at it from an enabling point-of-view, but in my opinion, having it return true on objects (!= 'classes') still is the lesser evil.

-- Paragraphing: There was a bug in my blog that stopped newlines whenever a CODE block was used. Fixed.

#26. Onno Marsman on 29 December 2008

Gravatar.com: Onno MarsmanAh thanks, now at last I can make my posts readable. Let's see if this works...


About configuration: there's the danger of a lot of discussions being settled with "let's make it configurable" and that will make a lot of things unclear. Without wanting to start a discussion about that topic, in my opinion, this is exactly where most open source PHP CMS products known to me take a wrong turn. You get a lot of imaginary spin offs only by personal preference configuration which have to be maintained, and this causes a lot of bugs: a programmer tends to find and solve a bug only with his preferable configuration.

... [more]
Especially with a project like this which is generally very simple, I think we should put a lot of effort in keeping it simple. If we have to make decisions we can't all agree with: too bad. Even if I would be the only one to think something should be solved differently and therefor it wouldn't be done that way, I probably wouldn't agree on making it configurable. This would be the case in the discussion about is_array right here: it's just not important enough.

I'm not saying configuration shouldn't be there at all. There might be some cases where configuration can be a good thing, although I can't think of one right now. Anyway, I think, we shouldn't use it for settling a discussion, and only use it when there is really no alternative.


About configuration by function parameters: like you said, this is a really bad idea and shouldn't be considered an option indeed.


Of course, about all these issues, I can only speak for myself.... I wonder what Kevin has to say about all of these things. He has a lot of reading to do ;)

#25. Brett Zamir on 29 December 2008

Gravatar.com: Brett ZamirOnno: I thought so, but you could have been just doing it as a learning exercise. But, honestly, I wasn't targeting it at you really, I just felt I had to get that off my chest. :) Sorry about that.


I don't think that configuration is making things complicated unless the default behavior is unreasonable. Although it's usually nicer to do it by passing in an argument (if you like the PHP-style that is), since we don't really have that option, I think offering a choice is convenient and allows the library to be shared more widely. Imagine, for example, just keeping your PHP functions followed by configuration setup (if you felt the need to customize) all in one file. You could just reuse that without needing to worry about it.

... [more]
What do you think about the idea of adding a module property and constants?


For paragraphing, as I only discovered this last post, was to make two lines between each.

#24. Onno Marsman on 28 December 2008

Gravatar.com: Onno MarsmanBrett: I'm of course talking about this function (and some other) and not the complete library, why else would I bother to participate in any way? You're defending the need of the whole library to me: you really don't need to, I share your opinion about that obviously.
--------
The in_array function seems useful to me too when you consider the whole frame/window issue, but that's a problem I don't think I will encounter very often. And when it would return true on objects (as it does now) that whole problem wouldn't even exist, and the function would seem useless to me anyway. And that's why I'm saying I probably would never use this function. My point on configuration making things complicated remains.
------
One more question to you, Brett: could you please tell me how to post in paragraphs on this site? My posts continue to result in large ugly blobs of text.

#23. Brett Zamir on 28 December 2008

Gravatar.com: Brett ZamirHi Onno: Well, for this function alone it would no doubt be overkill (the OOP way), but I don't think that PHP-JS is merely useful in helping students of PHP transition to JS, though that is a good benefit.


What is useful, I think, is that PHP has defined a vocabulary for a wide range of standard processing people want to do on Strings, Arrays, etc., functions which are completely lacking in JavaScript--a language that was standardized early on, and had little time to acquire even basic utility facilities, despite it being a flexible language).

... [more]
PHP provides a kind of expressive vocabulary to be able to do things, and with which many users may already be familiar with the terminology. No doubt a large part of what people like about PHP is its large number of functions.


And for is_array(), I think many experienced programmers would be glad to save themselves the trouble of having to type the same long fail-safe string over and over again that you all were discussing (to avoid the different window/frame problem).


Personally speaking, I'm more drawn to the utility (and elegance) of other functions like array_values() or array_keys(), or even in_array(). I don't want to have to write a for loop every time I need one of them or even when I can use "indexOf() !== -1", in_array() is so much more elegant. Seriously, what's wrong with saving yourself time and making your code more intelligible?


Of course, some will look down on this because either this is not the "JavaScript way" (if it's OOP, saves lines of code, and doesn't have any negative side effects, I don't see how it isn't) or because it pays homage to a language which is just too darn easy to learn and do useful things with.


It's like people who will respect you if you learn ancient Egyptian but think nothing of you learning Spanish. If it's useless and difficult, then it deserves praise. Or when people prefer the status quo of not having an official world auxiliary language because they think it is charming that we can't communicate with each other (or just expect that everyone should spend all of their time mastering various languages, rather than working for a global agreement to have one language (whether English, Esperanto, or whatever could garner the most support) be taught along with native languages in schools around the world). Does humanity really need scores of words for "apple" when we could settle on one language in addition to our native one? (thousands of words, I know, but I'm only talking about reducing lingua francas, not native languages) Does inter-communication need to be only for those with privilege and too much free time?


Why does a JavaScript library (that has no JavaScript standard to work from) need to start from scratch as far as terminology as well as functionality? Isn't it helpful to be able to piggy-back on something already existing?


Sorry for this diatribe (I'm not at all responding to your honest question), but this just raised the topic for me of all the maligning people do
in other discussions I've had because human beings like to lord over the "right way", and conversely, proponents of practicality are often too cowed to defend the useful albeit ordinary, while others are afraid to think for themselves and resist the impulse to second-guess oneself when everyone else is criticizing something you find useful. Criticism itself is usually such a waste of time, where we should be honestly discussing in a humble manner (like your nice polite but frank question) which way is better.


I'm doing JavaScript for full-time paid work (building Firefox extensions), and I've unabashedly been using some of these utilities. I particularly like array_unique(), trim, and Mozilla equivalents I've made for file_get_contents() and file_put_contents().


Oh, and I see I'm using your min() function too! :) Given that you found a need to write a good many lines of code for that function, do you really want to rewrite that each time you need it or give it a non-PHP name? :)

#22. Onno Marsman on 28 December 2008

Gravatar.com: Onno MarsmanBrett: Isn't this making things a bit to complicated for something that's just meant to help a PHP programmer make the step to JS? I mean: no experienced JS programmer is ever gonna use this function anyway and I don't think a not so experienced one would wanna find out how to configure something like this. I think it would even be easier and clearer to fall back to "instanceof Array" or "instanceof Object", whichever one they need.
PHP doesn't have this kind of configuration either and if we would introduce it I doubt anybody would use it.

#21. Brett Zamir on 28 December 2008

Gravatar.com: Brett ZamirSorry, my OOP code had a bug...Here's a fix:

function PHP_JS (config) {
this.JS = {};
for (var php_js_method in this) { // Add JS config property for all PHP-JS functions
if (typeof this[php_js_method] === 'function') {
this.JS[php_js_method] = {};
}
}
for (var method in config) {
var configObj = config[method];
this.JS[method] = configObj;
}
}
PHP_JS.prototype = {
is_array : function (mixed_var) {
if (this.JS.is_array.objectsAsArrays) {
return (mixed_var instanceof Object);
}
return mixed_var && !(mixed_var.propertyIsEnumerable('length')) && typeof mixed_var === 'object' && typeof mixed_var.length === 'number';
}
}
 
var PHP1 = new PHP_JS({is_array:{objectsAsArrays:true}});
var PHP2 = new PHP_JS({is_array:{objectsAsArrays:false}});
alert( PHP1.is_array({}) ); // true
alert( PHP2.is_array({}) ); // false
PHP1.JS.is_array.objectsAsArrays = false; // Can still reconfigure if needed too
PHP2.JS.is_array.objectsAsArrays = true;
alert( PHP1.is_array({}) ); // false
alert( PHP2.is_array({}) ); // true

#20. Brett Zamir on 28 December 2008

Gravatar.com: Brett ZamirIn order for PHP-JS to work as a bona-fide framework (which I think it could well become), there is a need for configurability, as seen in this discussion. And while a decision must still be made as to default behavior, I think that we can take advantages features of JavaScript which PHP does not have, in order to allow that configurability without adding additional arguments to the functions (which might have additional ones assigned by PHP in the future): adding properties to the functions themselves. (My apologies if others have suggested this.)

My suggestion is to reserve "JS" as an object for configurability. For example, one might do:

function is_array (mixed_var) {
if (arguments.callee.JS.objectsAsArrays) {
return (mixed_var instanceof Object);
}
return mixed_var && !(mixed_var.propertyIsEnumerable('length')) && typeof mixed_var === 'object' && typeof mixed_var.length === 'number';
}
is_array.JS = {};
 
is_array.JS.objectsAsArrays = true;
alert( is_array({}) ); // true
is_array.JS.objectsAsArrays = false;
alert( is_array({}) ); // false


The internal code would simply check for "if ({func_name}.JS.{prop_name})", (adding the empty JS object right after the function declaration) and act accordingly. I believe this could really be useful, especially for functions with no easy parallel in native JavaScript, but where the nature of JavaScript suggests different possible behaviors for the functions (or for adding other ideas PHP didn't think of).

We might even handle this in an OOP way (to more easily allow different configurations for the functions in different contexts), if the "namespace" for our PHP-JS objects were to be given by a constructor function. For example,

var PHP1 = new PHP_JS({is_array:{objectsAsArrays:true}});
var PHP2 = new PHP_JS({is_array:{objectsAsArrays:false}});
alert( PHP1.is_array({}) ); // true
alert( PHP2.is_array({}) ); // false
PHP2.JS.is_array.objectsAsArrays = true; // Can still reconfigure if needed too
alert( PHP2.is_array({}) ); // true
 
function PHP_JS (config) {
this.JS = {};
for (var php_js_method in this) { // Add JS config property for all PHP-JS functions
if (typeof this[php_js_method] === 'function') {
this.JS[php_js_method] = {};
}
}
for (var method in config) {
var configObj = config[method];
this.JS[method] = configObj;
}
}
PHP_JS.prototype = {
is_array : function (mixed_var) {
if (arguments.callee.JS.objectsAsArrays) {
return (mixed_var instanceof Object);
}
return mixed_var && !(mixed_var.propertyIsEnumerable('length')) && typeof mixed_var === 'object' && typeof mixed_var.length === 'number';
}
}


Whether using the OOP approach or not, your configuration questions (objectsAsArrays, functionsDisallowed, etc.) could be handled.

For either of these approaches (of adding properties to the functions or namespace object), PHP constants could be added relating to that function (thus not requiring defining every possible PHP constant or polluting the global namespace further), or meta-data could be attached relating to that function vis-a-vis PHP such as to indicate to which module it belongs (or put the constants within the module information). Thus, a property could be used to indicate to which PHP module a given function belonged (if one was not already using namespaces to do so). Then one could do things like: extension_loaded(), get_loaded_extensions(), get_extension_funcs(), and get_defined_constants(true) as these functions could reflect upon the meta-data stored for each function.

Although the following is not strictly PHP behavior since Array functions are not an extension in PHP (though we can override this with configuration as described above), we could do things like:

if (!extension_loaded('array')) {
function is_array () {
....
}
function in_array () {
....
}
....etc.
}

#19. Onno Marsman on 27 December 2008

Gravatar.com: Onno MarsmanWow, that's really weird! I guess your find is a better implementation than "instanceof Array" then. I'm curious about what Kevin thinks about all of this now.

#18. T.Wild on 27 December 2008

Gravatar.com: T.WildTo be honest, Onno, put like that I would have to agree. Better to have it return false and know why then work around it, than have something you think works but be unable to explain why it goes wrong. I still feel that closer PHP behavior should be the goal, and returning true on associative arrays [objects] does this, but I guess you are unlikely to ever get this because of the basic fact that arrays are objects. So what's my decision? I'd have to say the former, but I'm left sitting on the fence somewhat. :)
------------------------------------
Now, if this function does get converted to returning true on TRUE arrays only, when I've been looking around the internet I found this version of is array:
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays#quickIDX34

function isArray(testObject) {   
return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

I did wonder why something like this was needed but i found an explanation on this site:
http://javascript.crockford.com/remedial.html

[value instanceof Array] will only recognize arrays that are created in the same context (or window or frame). JavaScript does not provide an infallible mechanism for distinguishing arrays from objects, so if we want to recognize arrays that are constructed in a different frame, then we need to do something more complicated.

P.S. I haven't found any real use for this outside PHP either.

#17. Onno Marsman on 27 December 2008

Gravatar.com: Onno Marsman@T.Wild: Returning true on objects doesn't mimic PHP any better than returning false would. You're looking at it from a "when should it return true" point of view. You could also look at it from a "when should it return false" point of view. From the "return false" point of view I can't really explain the current "return true on object and array" implementation, while "return true only on arrays" can be explained, I think, from both point of views.

About finding a reliable method: I'm pretty sure there isn't one.

Ah well, I would never use this function anyway and would do it the JS way, so I won't make any more fuss about this. I just would hate to see some functions of this library slip off into a state of "behaves a little but more like PHP on some fronts but is really confusing so nobody would ever dare to use it"

#16. T.Wild on 24 December 2008

Gravatar.com: T.WildI guess I'm just going to add fuel to the fire on this but IMO what JavaScript sees as an array/object isn't the issue but what PHP would since that's what we're trying to imitate is it not?
*
I agree in this sort of situation you just don't know what an object is intended as, but i think it's still better to return true for both arrays AND objects at least until a reliable method can be found to tell the difference between an object and an 'associative array', if one exists.

#15. Onno marsman on 17 December 2008

Gravatar.com: Onno marsmanHow should I post in paragraphs?[br]
[br]
test. If this worked... never mind ;)

#14. Onno Marsman on 17 December 2008

Gravatar.com: Onno MarsmanI guess you're missing my point.
I'm saying PHP's is_array checks the type of the variable, I think so should php.js' is_array.<br><br>

I mean: think of when you would you use this function. I think it would only make sense if you'd wanna check the type of a variable.<br><br>

For functions that expect arrays it's simple: we just treat objects as arrays. Here we just don't know what to expect and there really is no way of knowing whether an object is intended as an array or not.<br><br>

Remember the post from someone that wanted to create an array syntax like this:

array(" 'first' => 'kevin' ", " 'last' => 'Zonnevelt' " );

You agreed with me it would weird to create a new syntax that is not really the same as php, while js already has a syntax that is not really the same as php.<br>
I guess you could say the same about this issue: why create a new definition of what an array is that is not really the same as in php, while js already has a definition of what an array is that is not really the same as in php.

#13. Kevin on 17 December 2008

Member avatar: Kevin@ Onno Marsman: Yes, "associative array in JS is an object so it's not an array". But we're trying to implement PHP's is_array, and not JavaScript's definition of it.

Saying that PHP.JS should support associative arrays (objects), and making an exception for the most profound function in this category: is_array, is not making any sense.

What does make sense to me, is your argument that an array of functions is also an array. Thus scanning for functions to make a slight distinction between 'class-like-objects' and 'array-like-objects', can not be achieved that way.
... [more]
Insert insightfull comment here ;)

#12. Onno Marsman on 10 December 2008

Gravatar.com: Onno MarsmanAnd of course the current implementation is still the same as the following:

function is_array( mixed_var ) {
return (mixed_var instanceof Object);
}

#11. Onno Marsman on 10 December 2008

Gravatar.com: Onno MarsmanYou know I agree with you that php.js should support associative arrays. But I stay with my argument that is_array should return whether a variable is an array. An associative array in JS is an object so it's not an array.

About your example: I would argue what you are suggesting: check for false.

About scanning for functions: that results in some weird situations. We'd also have to change the implementation of is_object and it could theoretically result in situations where is_array returns true on a variable which after a few manipulations returns false. Furthermore: what to do with something like this:

var a = [function() { }];

Is this an object or an array, or both?
Or what if I would really just want to store some functions in an associative array? It is possible.
What I'm saying that the boundary just wouldn't be clear and that would just result in people not trusting these functions.

We should keep it simple: is_array is about type checking and returns true when it is an array. It's a very clear boundary, it is much easier to explain, defend and implement. Of course that doesn't mean we shouldn't support associative arrays.

#10. Kevin on 10 December 2008

Member avatar: Kevin@ Onno Marsman: Thanks for your input, the thought crossed my mind as well. Well, this is going to be dirty, so please buckle up Onno.. Please bear the following code:

var myResult, input = {'firstname': 'Onno', 'surname': 'Marsman'};
myResult = filterData(input); // Will only return array (object) on success
if (!is_array(myResult)) {
alert('Data could not be filtered!');
} else {
for (key in myResult) {
// process data
}
}


You can bet that people are going to use is_array in such ways.

Though you may argue that people 'd better use:
if (false === myResult) {

.. to check if filterData() worked correctly - and I would have agree with you, that doesn't mean that I want the first code to fail in php.js, just because we say that's not good coding habit. php.js isn't foolproof but we should try to make it whenever we face decisions like this.

Although it may even mean we have to scan for functions within objects to distinct them from associative arrays, I still think we have to stick with our idea of supporting associative arrays, and not make exceptions in this function.

I really do agree that is_object & is_array should differ though. So I will work on the function scanning. If you have any ideas on that (or still don't agree with me) please let me know.

#9. Onno Marsman on 04 December 2008

Gravatar.com: Onno MarsmanIsn't this the same as

return (mixed_var instanceof Object);

or
return (typeof mixed_var=='object');

?

Also: If mixed_var is an object which has functions then I don't think this function should return true. We could check for that, but in turn it makes you wonder what to do with the implementation of is_object. Does an object needs to have a function? I don't think so. This would mean that is_object(v) and is_array(v) can both be true at the same time, that doesn't make any sense when you think PHP.

In my opinion we're taking this to far. I think is_array is clearly meant to only check the type of the variable. I don't think we'll miss out an anything if it doesn't return true on associative arrays. In JS they just aren't arrays but objects so therefor imho for associative arrays is_array should return false and is_object should return true.

#8. Kevin on 01 December 2008

Member avatar: Kevin@ Manish: In php.js, javascript objects are indeed like php associative arrays

#7. Manish on 25 November 2008

Gravatar.com: Manishfunction is_array(input)
{
if( typeof input == 'object' && input instanceof Array )
{
return true;
... [more] }

return false;
}

#6. Kevin on 18 July 2008

Member avatar: KevinI'm nowhere near as good as I would like to be. But I'm trying. Glad you find these pages useful though.

#5. Marce on 07 July 2008

Default avatar:MarceTranks kevin, this function is good :), you are very good programer.

#4. Mat on 19 June 2008

Default avatar:MatGreat!

#3. Kevin on 04 January 2008

Member avatar: Kevin@ Andrey: Thank you I've updated the function!

#2. Andrey on 04 January 2008

Default avatar:AndreyI found a more simple sample:

function is_array(a) {
return (a instanceof Array);
}

#1. I. Stan on 04 January 2008

Default avatar:I. StanWouldn't this be better or is it not cross browser? I tested it successfully in IE6, FF2, Opera9 and Safari for Windows.

function is_array(a) {
return (a.constructor === Array) ? true : false;
}