» PHP.JS Namespaced
435 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_replace
- array_replace_recursive
- 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
- bcadd
- bccomp
- bcdiv
- bcmul
- bcround
- bcscale
- bcsub
- 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_alias
- 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
- error_get_last
- error_reporting
- escapeshellarg
- exit
- explode
- expm1
- exp
- extract
- fclose
- feof
- fgetcsv
- fgetc
- fgetss
- fgets
- filemtime
- filesize
- file
- file_exists
- file_get_contents
- floatval
- floor
- fmod
- fopen
- forward_static_call
- forward_static_call_array
- 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_extension_funcs
- get_headers
- get_html_translation_table
- get_included_files
- get_include_path
- 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
- i18n_loc_get_default
- i18n_loc_set_default
- 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
- metaphone
- method_exists
- microtime
- min
- mktime
- money_format
- 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
- restore_include_path
- 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_include_path
- set_time_limit
- sha1
- sha1_file
- shuffle
- sinh
- sin
- sizeof
- sleep
- sort
- soundex
- split
- sprintf
- sql_regcase
- sqrt
- strcasecmp
- strchr
- strcmp
- strcoll
- strcspn
- stream_context_create
- stream_context_get_default
- stream_context_get_options
- stream_context_get_params
- stream_context_set_default
- stream_context_set_option
- stream_context_set_params
- stream_get_contents
- stream_get_line
- stream_is_local
- 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
- trigger_error
- trim
- uasort
- ucfirst
- ucwords
- uksort
- uniqid
- unserialize
- urldecode
- urlencode
- user_error
- usleep
- usort
- utf8_decode
- utf8_encode
- var_dump
- var_export
- version_compare
- 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.
Thanks to a lot of extra effort by Michael White (http://crestidg.com) there now is a namespaced version of PHP.JS available for your coding pleasure.
Namespaces
Namespaces are used to group functions & objects together. In this case, all PHP.JS functions are contained in one big object: PHP_JS.
Look at this code (not namespaced):
/var/git/techblog/code/php_equivalents/examples/php.example.js
Easy typing right? Just like you know from PHP.
Now look at this code (namespaced):
/var/git/techblog/code/php_equivalents/examples/php.namespaced.example.js
Little bit different. All PHP.JS code is now stored in it's own object. Some people like that because it can then never conflict with any existing function names (either by you, your CMS, other libraries or even JavaScript itself). This becomes clear with abs:
a = Math.abs(-7.25); // Javascript's own abs() function a = $P.abs(-7.25); // php.js's abs() function a = abs(-7.25); // only recognized when using normal php.js
Other namespacing benefits
Namespacing makes PHP.JS more flexible and makes it easier for developers to extend and include this library. They have more control over this project because it listens to a single name. If you want to dig a little deeper, try wiki.
Unnamespaced PHP.JS
Both unnamespaced & namespaced versions will be maintained and updated.
Why? I know that there are a lot of people out there who do not want to switch to a namespaced variant because they just want to be able to call the functions directly. For the ease of typing, but also because it resembles PHP, and that's the whole point of this project, right?
Download php.js
You can do that on every function's page. But for your convenience:
- uncompressed source: php.namespaced.js (186.5kB)
- minified: php.namespaced.min.js (18kB with mod_deflate enabled)
- compressed: php.namespaced.packed.js (37.4kB)
Future features
We're currently working on two major project improvements.
Better Versioning
All functions are versioned, but we're working on solid versioning of the main php.js file as well, this feature will be ready really soon and announced here.
Lightweight
PHP.JS contains a lot of functions and you probably won't use them all in one site. So to people who are concerned with things like bandwidth I can recommend a couple of things:
- Try the minified version & mod_deflate
The combination will shrink the total php.js to 18kB - Only copy-paste the functions you need
The last suggestion is not very developer-friendly though. You will survive but still.. We've got the idea to create an online application with a lot of check boxes and a couple of default presets. To allow you to exclude all kinds of functions and totally customize your own PHP.JS. Your unique combination of functions will additionally generate a hash, so you can always enter that hash again to download the newest versions of your favorite functions.
Dedicated site
We're currently working on a dedicated site for PHP.JS. Moving this project away from my Blog will make it more accessible and help professionalize the project.
New to PHP.JS?
If you're new to PHP.JS, checkout an example. We are not trying to port or emulate the entire language or control structures of PHP. We don't see the need because JavaScript seems to have more elegant features in that category anyway.
However in our eyes, PHP does provide a large set of standard functions that make developing very easy, and some of them don't have good standard JavaScript implementations, though they often would be great to have client-side.
So in this project by also providing the functions separately, we hope to keep people from inventing the wheel and give them a head start.
About the project
The PHP.JS project started in December 2007. It quickly became populair and within 4 months PHP.JS supported over 120 PHP functions all translated to JavaScript altenatives. PHP.JS is open source and has received (and still is receiving) code contributions from 50+ developers around the world, who have all helped to make PHP.JS what it is today. A rich Javascript library that adds functionality & PHP compatibility to your projects.
You probably shouldn't follow me
Like this Article?
| I'd appreciate it if you leave a comment, spread the word, or consider a small donation |
RelatedArticles like this one» PHP.JS Licensing |
tags: programming, javascript, php, phpjs
category: Programming - Javascript - PHP equivalents
read: 24,937 times
Add Comment
PHP.JS is outgroing this blog and moving to it's own space. Please leave your comment here: http://phpjs.org
tagcloud
#96. Kevin on 02 February 2009
Because you can be sure that if somebody tries a port in the future, they will find the result of previous study in _unported.
#95. Brett Zamir on 02 February 2009
A potential use of this, especially on privileged JavaScript, like in a Firefox extension, would be to sure that incrementor or serialization code could be saved -to file, even if the user didn't completely load the page (say by unloading before the script executed or pushing the stop button).
But since it doesn't work in Firefox, I was more just throwing the functions out there. I didn't know ahead of time whether they would work. Maybe we could start a folder for items like this (as well as for ones that can't work in the PHP-way like list() ), so that we can move them to not porting, but still have some documentation for study purposes (or to resurrect them if support changes)?
#94. Kevin on 01 February 2009
And I can't see myself using these functions. But then again it may very well still be of use to many, and so it should be possible to add it if we attach clear warnings and don't include it in the default package.
But I have too little understanding of this side of JavaScript and so I think I should not be the person to making the final call.
... [more]
So if you still think there's a need: feel free to add these functions to the SVN repository.
#93. Brett Zamir on 31 January 2009
or also connection_aborted():
The event references to "abort" above might simply be changed to "unload" to prevent unloading (or noting whether the user is leaving), and this more clearly pertains to the action of not just one resource inside a document; however, it will not pertain to the user stopping a load, and again, in Firefox, while the unload event fires, it doesn't seem to work with the DOM standard preventDefault().
If you don't like either of these approaches, my guess is that these are otherwise not portable.
#92. Kevin on 25 January 2009
#91. Brett Zamir on 23 January 2009
#90. Kevin on 15 January 2009
But I don't want to implement mistakes actively ;) let's get it right, and then add them.
#89. Brett Zamir on 15 January 2009
As far as usort(), yes, it only works on indexed arrays at present. I thought it would be ok, since sort() and rsort() also only work on indexed arrays, and this was based on sort(). However, I do hope we can use the bubble sort technique at some point to get these functions (and add uasort() too) all supporting associative arrays.
By the way, although I see array_udiff_uassoc() was fixed, it is still in the unported list.
... [more]
all the best, Brett
#88. Kevin on 14 January 2009
Regarding Ext.Dev.: I installed it but got confused a bit. Couldn't find where to run my sources. Anyway I will have to give it some more time I guess.
About usort. Could it be that it only works on indexed arrays?
#87. Brett Zamir on 14 January 2009
#86. Brett Zamir on 14 January 2009
Thanks for adding all of the functions. Two small issues:
1) array_udiff_uassoc() lists array_uintersect_uassoc instead (and I guess maybe that's also why the former still shows in the unported list).
... [more]
2) I also added usort on http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_ksort/
I know it was a lot to keep track of with all the pasting, etc. Best, Brett
#85. Kevin on 14 January 2009
Tried but didn't quite get Extension Developer's Extension. Anyway I mapped testlast.sh toi my netbeans 'Run Project' button. Which will scan for the source file with the most recent modification date, and feed that to phpjstest.php
So basically I can work on source & test it all in my IDE.
#84. Brett Zamir on 13 January 2009
(Not sure if I've recommended it before, but the Extension Developer's Extension for Firefox makes for very quick JS testing in the browser. I prefer using the XUL editor for JavaScript to get immediate results from alerts, but there is a JS environment (whose print() feature is nice when alert is too cumbersome)--both of which are very convenient to add as custom toolbar buttons. I swear this has contributed more to my productivity in JS than almost anything)
#83. Kevin on 13 January 2009
The output gives an array in which the fist element has key: 0 and value: <empty array>
Could it be that rhino is doing this? There have been some issues (https://bugzilla.mozilla.org/show_bug.cgi?id=419090)
#82. Brett Zamir on 13 January 2009
#81. Kevin on 13 January 2009
With the array functions I had to stop at array_uintersect because that returned:
Whereas the PHP manual says the first element's value should be 'red'. Once that bug is taken care off I'll add the others as well.
I made strval depend on gettype (which depends on is_array), to avoid any future inconsistency issues.
And you are right: those are important issues we need to address!
#80. Brett Zamir on 12 January 2009
1) I think the most serious need to address sooner rather than later (my own additions included) is to avoid the problem PHP is having in converting its functions to fully support Unicode. Although JavaScript is a bit better off because it uses (usually) fixed width characters, in the case of certain characters (outside of the BMP (Basic Multi-lingual Plane)), these can be twice as long, so sometimes a "character" must be considered to be two characters long, if PHP-JS is to handle them properly.
(See "fixedFromCharCode()" at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/fromCharCode and a similar discussion at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/charCodeAt#Description )
... [more]
2) All "instanceof Array" tests (I've been adding some myself I know) should be changed into is_array() dependencies
3) One very interesting application of a full version of PHP-JS (esp. a while down the road) in case you hadn't considered it, would be as an importable module in Mozilla: https://developer.mozilla.org/en/Using_JavaScript_code_modules . Mozilla/Firefox only loads these once, so if one extension uses it, any number of others can without a loading cost.
#79. Brett Zamir on 12 January 2009
#78. Brett Zamir on 11 January 2009
I joked that I'd be find breathing, eating, and sleeping JavaScript :) Seriously, I was just taking the day off, but needed some fun brain engagement...
Here are sixteen array functions, the diff and intersect ones (they were all pretty closely related):
If you change the line:
to:
you can have array_intersect_assoc() as well.
If you change the line instead to:
you can have array_intersect_key().
Now for the diffs:
And if you change the line:
to:
...you get array_diff_assoc
If you change it instead to:
...you get array_diff_key.
Now for the single callback intersect types...
If you change this line:
to:
... you get array_intersect_ukey
Or if you changet the line to:
... you get array_intersect_uassoc
and if you change the line to:
... you get array_uintersect_assoc
Now for the single callback diff types:
If you change this line
to:
...you get array_diff_ukey.
If you change it instead to:
...you get array_diff_uassoc.
And if you change it to:
...you get array_udiff_assoc
And now for the double callback intersect function:
And, finally, for the double callback diff function:
#77. Kevin on 08 January 2009
#76. Brett Zamir on 08 January 2009
Here's a strtok implementation:
#75. Brett Zamir on 08 January 2009
#74. Brett Zamir on 08 January 2009
The above may need some further tweaking (e.g., I don't know if the __clone() method itself should be removed from the new object).
#73. Brett Zamir on 08 January 2009
#72. Brett Zamir on 08 January 2009
#71. Brett Zamir on 07 January 2009
#70. Brett Zamir on 07 January 2009
#69. Kevin on 07 January 2009
#68. Brett Zamir on 07 January 2009
#67. Brett Zamir on 07 January 2009
So, if I can push my luck, how about reconsidering register_shutdown_function()? Why was that rejected earlier? Given my interpretation of "shutdown" as relating to a window closing, I think that is consistent with other functions here.
I think you should change list() to "do not port" because I just don't see any way JavaScript can do such a thing, since functions are not allowed as l-values in JavaScript... (unless you wanted to reserve the list() page to point out the existence of array destructuring for people looking for an equivalent).
Also, again, not a big deal, but under my name, I'm credited twice for array_fill_keys.
I still mean to get back to you about get_defined_constants().
Here's extract() too by the way...
#66. Kevin on 31 December 2008
We've had the pleasure of dealing with a lot of functions that do not pose such dilemmas like: str_replace, addslashes. Those are merely a technical challenge.
But my point is: if it's technically possible, doesn't mean we should always do it. When porting functions to client side we have to ask ourselves questions like:
... [more] - is there a clear & (reasonably) undisputed outcome
- can it do any (unintended) harm
- etc
Now, back to exit: Besides the fact that this would be problematic for my testsuite (no reason not to port), for me this is a function that's in the gray area, it's not as 'black' as getmygid (which will never ever be ported), it's not as 'white' as str_replace. It has it's sharp edges. But I would be willing to add your implementation to the library, and see what responses we get. Maybe exclude it from the default compile.
#65. Brett Zamir on 31 December 2008
One can just use throw '', as mentioned, but it is annoying that it pollutes your Error Console at a time when you're already looking trying to figure out errors.
While it is nice to consider the potential uses of course, I tend to think:
1) People are usually creative enough to think of uses for functionalities that we do not envision. How many times do I find myself wishing a programmer or API creator had just implemented the spec (or otherwise offer greater access) and not tried to anticipate all uses or prevent what in their opinion was "bad" coding (though which actually had its uses). We consumers should be able to take the risks we want, as long as they are wholly unnecessary ones.
2) For the sake of students of JavaScript, seeing the closest equivalents for familiar constructs is itself instructive.
3) Including functions may lead to proposals for better implementations
Very good point about events continuing to fire--Although the following wouldn't stop events like setInterval(), synthetic events, etc., it registers capturing event listeners for all of the major events on the window object, with these stopping further propagation (could be made to prevent default behavior too by uncommenting e.preventDefault()).
Maybe there's a better way (any DOM copy/import operations that could be done for the window or document which lose events in the process?)
#64. Onno Marsman on 30 December 2008
But very creative indeed.
... [more]
I think window.close() would be even more like exit in the sense that it says: "Just stop everything now!" but I wouldn't want to go there ;)
#63. Brett Zamir on 30 December 2008
On a slippery slope to what? Are you worried about code that is more likely to be platform-specific?
In any case, I think you can include or exclude whatever you like, though I think it'd be great if you were able to still leave the functions that don't make it into the library in the comments at this site (or to your new site), so people searching the site might still find them if they wanted to use them.
... [more]
My personal thought is that people can always ignore what they don't want to use (and given the size and potential size of the project, I think people will have to pick only the ones they want anyways). But it's your call...
#62. Kevin on 30 December 2008
I do think you have been very creative by taking the 'throw' approach to implement an exit function, and I guess it could work fine.
On the other hand, I feel we start down a slippery slope with these functions and my inner programmer is telling me to stick with notporting.
... [more]
Good arguments may very well change that. So bring it on.
#61. Brett Zamir on 20 December 2008
Brett
#60. Brett Zamir on 20 December 2008
#59. Brett Zamir on 20 December 2008
function exit (status) {
window['ExitError'] = function (status) {
this.status = status;
... [more] };
if (typeof status === 'string') {
alert(status);
}
throw new ExitError(status);
}
try {
exit("It's all over");
}
catch (e) {
if (!(e instanceof Error)) {
throw e; // Can catch all other errors, but let 'exit' work
}
}
try {
exit("It's all over");
}
catch (e) {
if (e instanceof ExitError) {
alert('We can also catch the exit() if we want to');
}
}
#58. Brett Zamir on 20 December 2008
function exit (status) {
if (typeof status === 'string') {
alert(status);
... [more] }
throw status;
}
exit('abc');
#57. Brett Zamir on 20 December 2008
Here's one to handle the function as a string:
#56. Brett Zamir on 20 December 2008
Here's another one...
I could try something with Mozilla-specific code when the whole application is shutting down, if you were open to using browser-specific stuff (for my uses, that is more cool for file_get_contents() type of functions too).
#55. Kevin on 17 December 2008
#54. Brett Zamir on 17 December 2008
#53. Brett Zamir on 17 December 2008
#52. Brett Zamir on 17 December 2008
I made an unported list myself for the arrays before I knew about your list... With the addition of the following submission, all remaining PHP array functions are about diffs, intersects, sorts, or seem to be not really suitable in JavaScript (except maybe for study purposes). Note that the following works with associative arrays (as with regular ones): as input and, if needed, as output. Again, I've commented out sections dealing with array-like objects in case anyone wants to add the code back in.
#51. Kevin on 10 December 2008
@ Brett Zamir: If you want you can also track our 'unported' function list:
http://trac.phpjs.org/projects/phpjs/browser/trunk/_unported
#50. Paulo Ricardo F. Santos on 04 December 2008
#49. Paulo Ricardo F. Santos on 04 December 2008
Whew! :P
#48. Brett Zamir on 03 December 2008
#47. Brett Zamir on 03 December 2008
Here's compact(), but with what I believe is an inevitable limitation on scope. Example is based on the PHP manual's, but with two extra bits of data added.
#46. Kevin on 03 December 2008
#45. Paulo Ricardo F. Santos on 03 December 2008
As far I've tested, it's Ok. The only difference is that JS supports only 3 decimal digits for milliseconds. ;/
This one seems to match the exact PHP behavior. As far I known, there's no locale influence, so, it might be correct.
As always, improvements are welcome. :)
Thanks for your thanks, Kevin. I'm glad to contribute with this brilliant project. =)
#44. Kevin on 03 December 2008
#43. Paulo Ricardo F. Santos on 03 December 2008
In my tests all it's Ok, lacks only the HTTP/version of HTTP response (key 0). Anyway, it's open to improvements. :)
8)
#42. Paulo Ricardo F. Santos on 02 December 2008
Sorry for the flood. =/
#41. Paulo Ricardo F. Santos on 02 December 2008
Also, another contribution:
It lacks the third parameter - it's not possible to implement in JS - but remains useful, a time that could be used to declare constants in browsers that don't support the 'const' keyword. :)
#40. Paulo Ricardo F. Santos on 02 December 2008
=)
#39. Paulo Ricardo F. Santos on 02 December 2008
;-)
#38. Paulo Ricardo F. Santos on 01 December 2008
;)
#37. Kevin on 01 December 2008
#36. Paulo Ricardo F. Santos on 01 December 2008
Improvements are welcome. :)
#35. Kevin on 18 November 2008
#34. Brett Zamir on 16 November 2008
#33. Brett Zamir on 16 November 2008
#32. Brett Zamir on 16 November 2008
Following is an array_merge() to work with associative arrays/objects as well as arrays. If only arrays are supplied, it returns an array.
I've also included two equivalent examples based on the PHP manual page for you to test with (if you like):
Thanks again for your work!
#31. Brett Zamir on 15 November 2008
#30. bassam essa on 14 November 2008
#29. Kevin on 13 November 2008
#28. Brett Zamir on 11 November 2008
A key could be a float, so I think that ought to be treated as an object (i.e., preserve the key as a float regardless of the preserve_keys argument) rather than as an array?
#27. Brett Zamir on 10 November 2008
You need to keep the text I had at the end of the function to handle plain arrays (which keeps them as plain arrays):
If you want to delete or comment out the
...go ahead. That was intended for the arguments object (which wouldn't get changed by reference). That is another contribution which is intended to handle the JavaScript-style array-like objects (arguments at least), so to mimic the PHP-style without fear of unintended effects, you could comment that out as well (My personal preference is to comment out rather than delete since it could be handy to have there for people who want to use the PHP-equivalent functions on common JavaScript constructs).
best wishes, Brett
#26. Kevin on 09 November 2008
But the first example is failing. And though the length item may be handy, it's asstraying from the PHP-way, which may leed to unexpected behaviour when developers implement this.
Also i notices the:
Which changes the original argument arr by references. Also unexpected & undesired behaviour I think.
#25. Brett Zamir on 04 November 2008
but I don't know how one could reliably iterate through array-like objects like DOM Node lists without also grabbing the methods (one could test that the property was numeric, but one would need code to distinguish between such cases as these where the non-numeric items should be avoided and other cases (as in associative arrays) where they would be kept).
#24. Brett Zamir on 04 November 2008
If you don't want a length property added to the object (or don't want to accept them), just remove this line:
and the 'if' condition (but not the code inside):
However, I thought it could be useful to allow for array-like objects, which, while they don't preserve the 'length' property dynamically or have array methods, still can be iterated (like the arguments object): http://books.google.com/books?id=VOS6IlCsuU4C&pg=PA122&lpg=PA122&dq=definitive+guide+javascript+%22array-like+objects%22&source=bl&ots=wHOcIU9yyX&sig=0fzUC3jnWDanqoOXvf4kY-4QtfA&hl=en&sa=X&oi=book_result&resnum=5&ct=result#PPA122,M1
But, I'd understand it if you wanted to forgo that...
#23. Kevin on 03 November 2008
returned:
Instead of the expected:
#22. Brett Zamir on 02 November 2008
#21. Brett Zamir on 02 November 2008
#20. Brett Zamir on 02 November 2008
Anyways, as far as array_slice, in the case of this function, PHP also does not support associative arrays. However, I did add the one missing argument, preserve_keys, which must return an array-like object in JavaScript (though it is still a numeric array in PHP) if this argument is true (and the offset is not 0).
function array_slice(arr, offst, lgth, preserve_keys) {
... [more] if (preserve_keys && offst != 0) { // Can go with genuine array if offst is 0
offst = (offst < 0) ? arr.length - offst : offst;
lgth = !lgth ? arr.length : (lgth < 0) ? arr.length + lgth : lgth;
var assoc = {};
for (var i=offst, arrlgth=0; i < lgth; i++, arrlgth++) {
assoc[i] = arr[i];
}
assoc.length = arrlgth; // Make as array-like object (though length will not be dynamic)
return assoc;
}
if (lgth === undefined) {
return arr.slice(offst);
}
else if (lgth >= 0) {
return arr.slice(offst, offst + lgth);
}
else {
return arr.slice(offst, lgth);
}
}
#19. p on 22 October 2008
trying to run some simple samples with the namespaced version but only getting error....
- FF Errorconsole says : $P is not defined
- IE says $P is null or not an object
... [more] The UNnamespaced version works with no errors
I'm probably overlooking something (simple) but dunno what....... :-(
#18. Kevin on 20 October 2008
About the wiki: We're working on http://phpjs.org, which will have a lot of cool features once it's done. We also have a developer wiki, so we're pretty set on that. Thanks though.
#17. Brett Zamir on 18 October 2008
Just wanted to offer the following functions. Perhaps someone clever can think of a better way to do them, but I offer them for what it's worth...
Again, I make my offer to use the wiki at http://javascript.wikia.com/wiki/PHP-Javascript . Thanks for collecting these great treasures!
#16. Stefan Sturm on 06 October 2008
Great to hear...
Thanks for your work,
... [more] Stefan Sturm
#15. Kevin on 06 October 2008
#14. Stefan Sturm on 05 October 2008
whats about changing the doc style, so we can use it modern IDE'S like Netbeans?
Greetings,
... [more] Stefan Sturm
#13. Kevin on 02 October 2008
#12. Chris on 02 October 2008
#11. Kevin on 27 August 2008
#10. Jackson on 14 August 2008
#9. Kevin on 16 June 2008
#8. Charel B on 15 June 2008
#7. Sincklation on 17 April 2008
#6. Kevin on 08 April 2008
#5. Weston Ruter on 08 April 2008
#4. Kevin on 02 April 2008
#3. _argos (waldo malqui silva) on 01 April 2008
I'm back :p, for my work I need these 2 functions ip2long and long2ip I sent U.
#2. Dharmavirsinh Jhala on 29 March 2008
PHP.JS has been part of my common javascript library and now it has namespace too..
http://blogs.digitss.com
#1. BTM on 29 March 2008