» Javascript equivalent for PHP's is_array
399 PHP equivalents
- PHP.JS Licensing
- PHP.JS SVN
- PHP.JS Namespaced
- abs
- acosh
- acos
- addslashes
- 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
- array
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_fill
- array_fill_keys
- array_filter
- array_flip
- array_intersect
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_keys
- array_key_exists
- array_map
- array_merge
- array_merge_recursive
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff
- array_udiff_assoc
- array_udiff_uassoc
- array_uintersect
- array_uintersect_assoc
- array_uintersect_uassoc
- array_unique
- array_unshift
- array_values
- array_walk
- array_walk_recursive
- arsort
- asinh
- asin
- asort
- assert
- assert_options
- atan2
- atanh
- atan
- base64_decode
- base64_encode
- basename
- base_convert
- bin2hex
- bindec
- call_user_func
- call_user_func_array
- ceil
- checkdate
- chop
- chr
- chunk_split
- classkit_import
- classkit_method_add
- classkit_method_copy
- classkit_method_redefine
- classkit_method_remove
- classkit_method_rename
- class_exists
- compact
- constant
- convert_uuencode
- cosh
- cos
- count
- count_chars
- crc32
- create_function
- ctype_alnum
- ctype_alpha
- ctype_cntrl
- ctype_digit
- ctype_graph
- ctype_lower
- ctype_print
- ctype_punct
- ctype_space
- ctype_upper
- ctype_xdigit
- current
- date
- date_default_timezone_get
- date_default_timezone_set
- date_parse
- deaggregate
- decbin
- dechex
- decoct
- defined
- define
- deg2rad
- die
- dirname
- doubleval
- each
- echo
- empty
- end
- exit
- explode
- expm1
- exp
- extract
- fclose
- feof
- fgetcsv
- fgetc
- fgetss
- fgets
- filemtime
- filesize
- file
- file_exists
- file_get_contents
- floatval
- floor
- fmod
- fopen
- fpassthru
- fread
- fseek
- ftell
- function_exists
- func_get_args
- func_get_arg
- func_num_args
- getdate
- getenv
- getlastmod
- getrandmax
- gettimeofday
- gettype
- get_cfg_var
- get_class
- get_class_methods
- get_class_vars
- get_declared_classes
- get_defined_constants
- get_defined_functions
- get_defined_vars
- get_headers
- get_html_translation_table
- get_included_files
- get_meta_tags
- get_object_vars
- get_required_files
- get_resource_type
- gmdate
- gmmktime
- gmstrftime
- gopher_parsedir
- hexdec
- htmlentities
- htmlspecialchars
- htmlspecialchars_decode
- html_entity_decode
- http_build_query
- hypot
- idate
- implode
- import_request_variables
- include
- include_once
- ini_alter
- ini_get
- ini_get_all
- ini_restore
- ini_set
- intval
- in_array
- ip2long
- isset
- » is_array
- is_binary
- is_bool
- is_buffer
- is_callable
- is_double
- is_finite
- is_float
- is_infinite
- is_integer
- is_int
- is_long
- is_nan
- is_null
- is_numeric
- is_object
- is_real
- is_resource
- is_scalar
- is_string
- is_unicode
- join
- json_decode
- json_encode
- key
- krsort
- ksort
- lcfirst
- lcg_value
- levenshtein
- localeconv
- localtime
- log10
- log1p
- log
- long2ip
- ltrim
- max
- md5
- md5_file
- method_exists
- microtime
- min
- mktime
- mt_getrandmax
- mt_rand
- natcasesort
- natsort
- next
- nl2br
- nl_langinfo
- number_format
- octdec
- ord
- parse_str
- parse_url
- pathinfo
- pclose
- phpversion
- php_ini_loaded_file
- php_ini_scanned_files
- php_strip_whitespace
- pi
- popen
- pos
- pow
- preg_grep
- preg_quote
- prev
- printf
- print_r
- property_exists
- putenv
- quoted_printable_decode
- quoted_printable_encode
- quotemeta
- rad2deg
- rand
- range
- rawurldecode
- rawurlencode
- readfile
- realpath
- register_shutdown_function
- require
- require_once
- reset
- restore_exception_handler
- rewind
- round
- rsort
- rtrim
- 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
- serialize
- setcookie
- setlocale
- setrawcookie
- settype
- set_exception_handler
- set_time_limit
- sha1
- sha1_file
- shuffle
- sinh
- sin
- sizeof
- sleep
- sort
- soundex
- split
- sprintf
- sql_regcase
- sqrt
- strcasecmp
- strchr
- strcmp
- strcoll
- strcspn
- strftime
- stripos
- stripslashes
- strip_tags
- stristr
- strlen
- strnatcasecmp
- strnatcmp
- strncasecmp
- strncmp
- strpbrk
- strpos
- strrchr
- strrev
- strripos
- strrpos
- strspn
- strstr
- strtok
- strtolower
- strtotime
- strtoupper
- strtr
- strval
- str_getcsv
- str_ireplace
- str_pad
- str_repeat
- str_replace
- str_rot13
- str_shuffle
- str_split
- str_word_count
- substr
- substr_compare
- substr_count
- substr_replace
- tanh
- tan
- timezone_abbreviations_list
- timezone_identifiers_list
- time
- time_nanosleep
- time_sleep_until
- trim
- uasort
- ucfirst
- ucwords
- uksort
- uniqid
- unserialize
- urldecode
- urlencode
- usleep
- usort
- utf8_decode
- utf8_encode
- var_dump
- var_export
- vprintf
- vsprintf
- wordwrap
PHP to Javascript Project: php.js
This 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
is_array(['Kevin', 'van', 'Zonneveld']);And that would return
trueExample 2
is_array('Kevin van Zonneveld');And that would return
falseExample 3
is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});And that would return
trueMore about this Project
Download php.js
To easily include it in your code, every function currently available is stored in
Normal
- uncompressed source: php.js
- minified: php.min.js [recommended]
- compressed: php.packed.js
Namespaced What is 'namespaced?'
- uncompressed source: php.namespaced.js
- minified: php.namespaced.min.js
- compressed: php.namespaced.packed.js
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:
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
articles and
comments. You may also find my
bookmarks interesting. Or
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. |
RelatedArticles like this one» PHP.JS Licensing |
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










tagcloud

#42. Kevin on 16 March 2009
Thanks a lot!!
#41. mk.keck on 06 March 2009
Why not let the user change dynamicly the behavior of is_array()?
#40. Brett Zamir on 10 February 2009
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
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
http://blog.360.yahoo.com/blog-TBPekxc1dLNy5DOloPfzVvFIVOWMB0li?p=916
#37. Kevin on 25 January 2009
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:
.. 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
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
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
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
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
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
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
@ 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
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
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
-- 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:
to produce:
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
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
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
--------
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
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
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
#20. Brett Zamir on 28 December 2008
My suggestion is to reserve "JS" as an object for configurability. For example, one might do:
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,
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:
#19. Onno Marsman on 27 December 2008
#18. T.Wild on 27 December 2008
------------------------------------
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
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
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
*
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
[br]
test. If this worked... never mind ;)
#14. Onno Marsman on 17 December 2008
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:
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
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
#11. Onno Marsman on 10 December 2008
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:
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
You can bet that people are going to use is_array in such ways.
Though you may argue that people 'd better use:
.. 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
or
?
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
#7. Manish on 25 November 2008
{
if( typeof input == 'object' && input instanceof Array )
{
return true;
... [more] }
return false;
}
#6. Kevin on 18 July 2008
#5. Marce on 07 July 2008
#4. Mat on 19 June 2008
#3. Kevin on 04 January 2008
#2. Andrey on 04 January 2008
function is_array(a) {
return (a instanceof Array);
}
#1. I. Stan on 04 January 2008
function is_array(a) {
return (a.constructor === Array) ? true : false;
}