Mustafa Turan

Temiz Günce: Bir öğrencinin web, yaşam, programlama, veritabanları, veriler üzerine kurşun kalemi.

JavaScript'i Php gibi kullanın

Aşağıdaki fonksiyonlar php deki işlem fonksiyonlarını birebir JavaScript'e çeviriyor

Js to PHP

/* 
 * More info at: http://kevin.vanzonneveld.net/techblog/article/phpjs_licensing/
 * 
 * This is version: 1.24
 * php.js is copyright 2008 Kevin van Zonneveld.
 * 
 * Portions copyright Michael White (http://crestidg.com), _argos, Jonas
 * Raoni Soares Silva (http://www.jsfromhell.com), Legaev Andrey, Ates Goral
 * (http://magnetiq.com), Philip Peterson, Martijn Wieringa, Webtoolkit.info
 * (http://www.webtoolkit.info/), Carlos R. L. Rodrigues
 * (http://www.jsfromhell.com), Ash Searle (http://hexmen.com/blog/),
 * Erkekjetter, marrtins, Alfonso Jimenez (http://www.alfonsojimenez.com),
 * Aman Gupta, Arpad Ray (mailto:arpad@php.net), Karol Kowalski, Mirek Slugen,
 * Thunder.m, Tyler Akins (http://rumkin.com), d3x, mdsjack
 * (http://www.mdsjack.bo.it), Alex, Alexander Ermolaev
 * (http://snippets.dzone.com/user/AlexanderErmolaev), Allan Jensen
 * (http://www.winternet.no), Andrea Giammarchi
 * (http://webreflection.blogspot.com), Bayron Guevara, Ben Bryan, Benjamin
 * Lupton, Brad Touesnard, Brett Zamir, Cagri Ekin, Cord, David, David James,
 * DxGx, FGFEmperor, Felix Geisendoerfer (http://www.debuggable.com/felix),
 * FremyCompany, Gabriel Paderni, Howard Yeend, J A R, Leslie Hoare, Lincoln
 * Ramsay, MeEtc (http://yass.meetcweb.com), Mick@el, Nick Callen, Ozh, Pedro
 * Tainha (http://www.pedrotainha.com), Peter-Paul Koch
 * (http://www.quirksmode.org/js/beat.html), Philippe Baumann, Sakimori,
 * Sanjoy Roy, Simon Willison (http://simonwillison.net), Steve Clay, Steve
 * Hilder, Steven Levithan (http://blog.stevenlevithan.com), T0bsn, Thiago
 * Mata (http://thiagomata.blog.com), Tim Wiel, XoraX (http://www.xorax.info),
 * Yannoo, baris ozdil, booeyOH, djmix, duncan, echo is bad, gabriel paderni,
 * ger, gorthaur, john (http://www.jd-tech.net), kenneth, loonquawl,
 * penutbutterjelly, stensi
 * 
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */ 

// {{{ array
function array( ) {
    // #!#!#!#!# array::$descr1 does not contain valid 'array' at line 258
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array/
    // +       version: 805.1716
    // +   original by: d3x
    // *     example 1: array('Kevin', 'van', 'Zonneveld');
    // *     returns 1: ['Kevin', 'van', 'Zonneveld'];
    return Array.prototype.slice.call(arguments);
}// }}}
// {{{ array_change_key_case
function array_change_key_case( array ) {
    // Changes all keys in an array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_change_key_case/
    // +       version: 804.1712
    // +   original by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // *     example 1: array_change_key_case(42);
    // *     returns 1: false
    // *     example 2: array_change_key_case([ 3, 5 ]);
    // *     returns 2: {0: 3, 1: 5}
    // *     example 3: array_change_key_case({ FuBaR: 42 });
    // *     returns 3: {"fubar": 42}
    // *     example 4: array_change_key_case({ FuBaR: 42 }, 'CASE_LOWER');
    // *     returns 4: {"fubar": 42}
    // *     example 5: array_change_key_case({ FuBaR: 42 }, 'CASE_UPPER');
    // *     returns 5: {"FUBAR": 42}
    // *     example 6: array_change_key_case({ FuBaR: 42 }, 2);
    // *     returns 6: {"FUBAR": 42}
    var case_fn, tmp_ar = new Object, argc = arguments.length, argv = arguments, key;
    if (array instanceof Array) {
        return array;
    }
    if (array instanceof Object) {
        if( argc == 1 || argv[1] == 'CASE_LOWER' || argv[1] == 0 ){
            case_fn = "toLowerCase";
        } else{
            case_fn = "toUpperCase";
        }
        for (var key in array) {
            tmp_ar[key[case_fn]()] = array[key];
        }
        return tmp_ar;
    }
    return false;
}// }}}
// {{{ array_chunk
function array_chunk( input, size ) {
    // Split an array into chunks
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_chunk/
    // +       version: 804.1712
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // *     example 1: array_chunk(['Kevin', 'van', 'Zonneveld'], 2);
    // *     returns 1: {0 : {0: 'Kevin', 1: 'van'} , 1 : {0: 'Zonneveld'}}
 
    for(var x, i = 0, c = -1, l = input.length, n = []; i < l; i++){
        (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]];
    }
    return n;
}// }}}
// {{{ array_combine
function array_combine( keys, values ) {
    // Creates an array by using one array for keys and another for its values
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_combine/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_combine([0,1,2], ['kevin','van','zonneveld']);
    // *     returns 1: {0: 'kevin', 1: 'van', 2: 'zonneveld'}
   
    var new_array = {}, keycount=keys.length, i;
    // input sanitation
    if( !keys || !values || keys.constructor !== Array || values.constructor !== Array ){
        return false;
    }
    // number of elements does not match
    if(keycount != values.length){
        return false;
    }
    for ( i=0; i < keycount; i++ ){
        new_array[keys[i]] = values[i];
    }
    return new_array;
}// }}}
// {{{ array_count_values
function array_count_values( array ) {
    // Counts all the values of an array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_count_values/
    // +       version: 804.1712
    // +   original by: Ates Goral (http://magnetiq.com)
    // + namespaced by: Michael White (http://crestidg.com)
    // *     example 1: array_count_values([ 3, 5, 3, "foo", "bar", "foo" ]);
    // *     returns 1: {3:2, 5:1, "foo":2, "bar":1}
    // *     example 2: array_count_values({ p1: 3, p2: 5, p3: 3, p4: "foo", p5: "bar", p6: "foo" });
    // *     returns 2: {3:2, 5:1, "foo":2, "bar":1}
    // *     example 3: array_count_values([ true, 4.2, 42, "fubar" ]);
    // *     returns 3: {42:1, "fubar":1}
    var tmp_ar = new Object(), key;
    var countValue = function (value) {
        switch (typeof(value)) {
            case "number":
                if (Math.floor(value) != value) {
                    return;
                }
            case "string":
                if (value in this) {
                    ++this[value];
                } else {
                    this[value] = 1;
                }
        }
    };
    if (array instanceof Array) {
        array.forEach(countValue, tmp_ar);
    } else if (array instanceof Object) {
        for ( key in array ) {
            countValue.call(tmp_ar, array[key]);
        }
    }
    return tmp_ar;
}// }}}
// {{{ array_diff
function array_diff (array) {
    // Computes the difference of arrays
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_diff/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sanjoy Roy
    // *     example 1: array_diff(['Kevin', 'van', 'Zonneveld'], ['van', 'Zonneveld']);
    // *     returns 1: ['Kevin']
    var arr_dif = [], i = 1, argc = arguments.length, argv = arguments, key, key_c, found=false, cntr=0;
    // loop through 1st array
    for ( key in array ){
        // loop over other arrays
        for (i = 1; i< argc; i++){
            // find in the compare array
            found = false;
            for (key_c in argv[i]) {
                if (argv[i][key_c] == array[key]) {
                    found = true;
                    break;
                }
            }
            if(!found){
                //arr_dif[key] = array[key];
                arr_dif[cntr] = array[key];
                cntr++;
            }
        }
    }
    return arr_dif;
}// }}}
// {{{ array_diff_assoc
function array_diff_assoc ( array ) {
    // Computes the difference of arrays with additional index check
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_diff_assoc/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_diff_assoc({0: 'Kevin', 1: 'van', 2: 'Zonneveld'}, {0: 'Kevin', 4: 'van', 5: 'Zonneveld'});
    // *     returns 1: {1: 'van', 2: 'Zonneveld'}
    var arr_dif = {}, i = 1, argc = arguments.length, argv = arguments, key, key_c, found=false;
    // input sanitation
    if( !array || (array.constructor !== Array && array.constructor !== Array && typeof array != 'object' && typeof array != 'array') ){
        return null;
    }
    // loop through 1st array
    for ( key in array ){
        // loop over other arrays
        for (i = 1; i< argc; i++){
            // find in the compare array
            found = false;
            if(argv[i][key]){
                found = true;
                break;
            }
            if(!found){
                arr_dif[key] = array[key];
            }
        }
    }
    return arr_dif;
}// }}}
// {{{ array_diff_key
function array_diff_key( object ) {
    // Computes the difference of arrays using keys for comparison
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_diff_key/
    // +       version: 804.1712
    // +   original by: Ates Goral (http://magnetiq.com)
    // *     example 1: array_diff_key({red: 1, green: 2, blue: 3, white: 4});
    // *     returns 1: {"red":1, "green":2, "blue":3, "white":4}
    // *     example 2: array_diff_key({red: 1, green: 2, blue: 3, white: 4}, {red: 5});
    // *     returns 2: {"green":2, "blue":3, "white":4}
    // *     example 3: array_diff_key({red: 1, green: 2, blue: 3, white: 4}, {red: 5}, {green: 6, blue: 7});
    // *     returns 3: {"white":4}
    // *     example 4: array_diff_key({red: 1, green: 2, blue: 3, white: 4}, {red: 5}, {red: 5});
    // *     returns 4: {"green":2, "blue":3, "white":4}
    var tpm_ar = new Object(), argc = arguments.length, argv = arguments, key, argidx, other;
    for (key in object) {
        tpm_ar[key] = object[key];
    }
    for (argidx = 1; argidx < argc; ++argidx) {
        other = argv[argidx];
        if (other instanceof Object) {
            for (key in other) {
                delete tpm_ar[key];
            }
        }
    }
    return tpm_ar;
}// }}}
// {{{ array_fill
function array_fill( start_index, num, mixed_val ) {
    // Fill an array with values
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_fill/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: _argos
    // *     example 1: array_fill(5, 6, 'banana');
    // *     returns 1: { 5: 'banana', 6: 'banana', 7: 'banana', 8: 'banana', 9: 'banana', 10: 'banana' }
    var key, tmp_arr = new Array();
    if ( !isNaN ( start_index ) && !isNaN ( num ) ) {
        for( key = start_index; key  input.length ) {
            for ( i = 0; i < ( newLength - input.length ); i++ ) { newArray [ i ] = pad_value; }
            pad = ( ( pad_size < 0 ) ? newArray.concat ( input ) : input.concat ( newArray ) );
        } else {
            pad = input;
        }
    }
    return pad;
}// }}}
// {{{ array_pop
function array_pop( array ) {
    // Pop the element off the end of array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_pop/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_pop([0,1,2]);
    // *     returns 1: 2
    // done popping, are we?
    if( !array.length ){
        return null;
    }
    return array.pop();
}// }}}
// {{{ array_product
function array_product ( input ) {
    // Calculate the product of values in an array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_product/
    // +       version: 804.1712
    // +   original by: _argos
    // *     example 1: array_product([ 2, 4, 6, 8 ]);
    // *     returns 1: 384
    var Index = 0, Product = 1;
    if ( input instanceof Array ) {
        while ( Index < input.length ) {
            Product *= ( !isNaN ( input [ Index ] ) ? input [ Index ] : 0 );
            Index++;
        }
    } else {
        Product = null;
    }
    return Product;
}// }}}
// {{{ array_push
function array_push ( array ) {
    // Push one or more elements onto the end of array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_push/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_push(['kevin','van'], 'zonneveld');
    // *     returns 1: 3
    var i, argv = arguments, argc = argv.length;
    for (i=1; i < argc; i++){
        array[array.length++] = argv[i];
    }
    return array.length;
}// }}}
// {{{ array_rand
function array_rand ( input, num_req ) {
    // Pick one or more random entries out of an array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_rand/
    // +       version: 804.1712
    // +   original by: _argos
    // *     example 1: array_rand( ['Kevin'], 1 );
    // *     returns 1: 0
    var Indexes = [];
    var Ticks = num_req || 1;
    var checkDuplicate = function ( input, value ) {
        var Exist = false, Index = 0;
        while ( Index < input.length ) {
            if ( input [ Index ] === value ) {
                Exist = true;
                break;
            }
            Index++;
        }
        return Exist;
    };
    if ( input instanceof Array && Ticks  0) {
        return array.shift();
    }
    
    return null;
}// }}}
// {{{ array_sum
function array_sum( array ) {
    // Calculate the sum of values in an array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_sum/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_sum([4, 9, 182.6]);
    // *     returns 1: 195.6
    var key, sum=0;
    // input sanitation
    if( !array || (array.constructor !== Array && array.constructor !== Object) || !array.length ){
        return null;
    }
    for(var key in array){
        sum += array[key];
    }
    return sum;
}// }}}
// {{{ array_unique
function array_unique( array ) {
    // Removes duplicate values from an array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_unique/
    // +       version: 805.211
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      input by: duncan
    // +    bufixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld']);
    // *     returns 1: ['Kevin','van','Zonneveld']
    var p, i, j, tmp_arr = array;
    for(i = tmp_arr.length; i;){
        for(p = --i; p > 0;){
            if(tmp_arr[i] === tmp_arr[--p]){
                for(j = p; --p && tmp_arr[i] === tmp_arr

;); i -= tmp_arr.splice(p + 1, j - p).length; } } } return tmp_arr; }// }}} // {{{ array_unshift function array_unshift( array ) { // Prepend one or more elements to the beginning of an array // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_unshift/ // + version: 805.3114 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Martijn Wieringa // * example 1: array_unshift(['van', 'Zonneveld'], 'Kevin'); // * returns 1: 3 var argc = arguments.length, argv = arguments, i; for (i = 1; i < argc; i++) { array.unshift(argv[i]); } return (array.length); }// }}} // {{{ array_values function array_values( input ) { // Return all the values of an array // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_values/ // + version: 804.1712 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: array_values( {firstname: 'Kevin', surname: 'van Zonneveld'} ); // * returns 1: {0: 'Kevin', 1: 'van Zonneveld'} var tmp_arr = new Array(), cnt = 0; for ( key in input ){ tmp_arr[cnt] = input[key]; cnt++; } return tmp_arr; }// }}} // {{{ compact function compact ( var_names ) { // Create array containing variables and their values // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_compact/ // + version: 804.1712 // + original by: _argos // * example 1: compact('var1', 'var2'); // * returns 1: {} var Index = 0, Matrix = {}; var process = function ( value ) { for ( var i = 0; i < value.length; i++ ) { var key_value = value [ i ]; if ( key_value instanceof Array ) { process ( key_value ); } else { if ( typeof window [ key_value ] !== 'undefined' ) { Matrix [ key_value ] = window [ key_value ]; } } } return true; }; process ( arguments ); return Matrix; }// }}} // {{{ count function count( mixed_var, mode ) { // Count elements in an array, or properties in an object // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_count/ // + version: 804.1712 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: _argos // * example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE'); // * returns 1: 6 // * example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE'); // * returns 2: 6 var key, cnt = 0; if( mode == 'COUNT_RECURSIVE' ) mode = 1; if( mode != 1 ) mode = 0; for (key in mixed_var){ cnt++; if( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){ cnt += count(mixed_var[key], 1); } } return cnt; }// }}} // {{{ end function end ( array ) { // Set the internal pointer of an array to its last element // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_end/ // + version: 806.1600 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Legaev Andrey // + revised by: J A R // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: end({firstname: 'Kevin', middle: 'van', surname: 'Zonneveld'}); // * returns 1: 'Zonneveld' var tmp_arr = {}; // We don't want to 'pop' the original array and reduce it's size tmp_arr = array; return tmp_arr.pop(); }// }}} // {{{ in_array function in_array(needle, haystack, strict) { // Checks if a value exists in an array // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_in_array/ // + version: 804.1712 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']); // * returns 1: true var found = false, key, strict = !!strict; for (key in haystack) { if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) { found = true; break; } } return found; }// }}} // {{{ range function range ( low, high, step ) { // Create an array containing a range of elements // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_range/ // + version: 804.1712 // + original by: _argos // * example 1: range ( 0, 12 ); // * returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] // * example 2: range( 0, 100, 10 ); // * returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] // * example 3: range( 'a', 'i' ); // * returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] // * example 4: range( 'c', 'a' ); // * returns 4: ['c', 'b', 'a'] var matrix = []; var inival, endval, plus; var walker = step || 1; var chars = false; if ( !isNaN ( low ) && !isNaN ( high ) ) { inival = low; endval = high; } else if ( isNaN ( low ) && isNaN ( high ) ) { chars = true; inival = low.charCodeAt ( 0 ); endval = high.charCodeAt ( 0 ); } else { inival = ( isNaN ( low ) ? 0 : low ); endval = ( isNaN ( high ) ? 0 : high ); } plus = ( ( inival > endval ) ? false : true ); if ( plus ) { while ( inival = endval ) { matrix.push ( ( ( chars ) ? String.fromCharCode ( inival ) : inival ) ); inival -= walker; } } return matrix; }// }}} // {{{ reset function reset ( array ) { // Set the internal pointer of an array to its first element // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_reset/ // + version: 804.1712 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Legaev Andrey // * example 1: reset({firstname: 'Kevin', middle: 'van', surname: 'Zonneveld'}); // * returns 1: 'Kevin' var first_elm, key; if (array.constructor === Array){ first_elm = array[0]; } else { for (key in array){ first_elm = array[key]; break; } } return first_elm; }// }}} // {{{ shuffle function shuffle( array ) { // Shuffle an array // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_shuffle/ // + version: 804.1712 // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // * example 1: shuffle(['Kevin', 'van', 'Zonneveld']); // * returns 1: true for(var j, x, i = array.length; i; j = parseInt(Math.random() * i), x = array[--i], array[i] = array[j], array[j] = x); return true; }// }}} // {{{ sizeof function sizeof ( mixed_var, mode ) { // Alias of count() // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_sizeof/ // + version: 804.1712 // + original by: Philip Peterson // - depends on: count // * example 1: sizeof([[0,0],[0,-4]], 'COUNT_RECURSIVE'); // * returns 1: 6 // * example 2: sizeof({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE'); // * returns 2: 6 return count( mixed_var, mode ); }// }}} // {{{ get_class function get_class(obj) { // Returns the name of the class of an object // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_get_class/ // + version: 804.1712 // + original by: Ates Goral (http://magnetiq.com) // + improved by: David James // * example 1: get_class(new (function MyClass() {})); // * returns 1: "MyClass" // * example 2: get_class({}); // * returns 2: "Object" // * example 3: get_class([]); // * returns 3: false // * example 4: get_class(42); // * returns 4: false // * example 5: get_class(window); // * returns 5: false // * example 6: get_class(function MyFunction() {}); // * returns 6: false if (obj instanceof Object && !(obj instanceof Array) && !(obj instanceof Function) && obj.constructor) { var arr = obj.constructor.toString().match(/function\s*(\w+)/); if (arr && arr.length == 2) { return arr[1]; } } return false; }// }}} // {{{ checkdate function checkdate( month, day, year ) { // Validate a Gregorian date // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_checkdate/ // + version: 804.1712 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: checkdate(12, 31, 2000); // * returns 1: true // * example 2: checkdate(2, 29, 2001); // * returns 2: false // * example 3: checkdate(03, 31, 2008); // * returns 3: true var myDate = new Date(); myDate.setFullYear( year, (month - 1), day ); return ( (myDate.getMonth()+1) == month ); }// }}} // {{{ date function date ( format, timestamp ) { // Format a local time/date // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_date/ // + version: 804.1712 // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) // + parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: MeEtc (http://yass.meetcweb.com) // + improved by: Brad Touesnard // + improved by: Tim Wiel // * example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400); // * returns 1: '09:09:40 m is month' // * example 2: date('F j, Y, g:i a', 1062462400); // * returns 2: 'September 2, 2003, 2:26 am' var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date()); var pad = function(n, c){ if( (n = n + "").length < c ) { return new Array(++c - n.length).join("0") + n; } else { return n; } }; var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"}; var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var f = { // Day d: function(){ return pad(f.j(), 2); }, D: function(){ t = f.l(); return t.substr(0,3); }, j: function(){ return jsdate.getDate(); }, l: function(){ return txt_weekdays[f.w()]; }, N: function(){ return f.w() + 1; }, S: function(){ return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'; }, w: function(){ return jsdate.getDay(); }, z: function(){ return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0; }, // Week W: function(){ var a = f.z(), b = 364 + f.L() - a; var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1; if(b 0); } } }, // Month F: function(){ return txt_months[f.n()]; }, m: function(){ return pad(f.n(), 2); }, M: function(){ t = f.F(); return t.substr(0,3); }, n: function(){ return jsdate.getMonth() + 1; }, t: function(){ var n; if( (n = jsdate.getMonth() + 1) == 2 ){ return 28 + f.L(); } else{ if( n & 1 && n < 8 || !(n & 1) && n > 7 ){ return 31; } else{ return 30; } } }, // Year L: function(){ var y = f.Y(); return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0; }, //o not supported yet Y: function(){ return jsdate.getFullYear(); }, y: function(){ return (jsdate.getFullYear() + "").slice(2); }, // Time a: function(){ return jsdate.getHours() > 11 ? "pm" : "am"; }, A: function(){ return f.a().toUpperCase(); }, B: function(){ // peter paul koch: var off = (jsdate.getTimezoneOffset() + 60)*60; var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off; var beat = Math.floor(theSeconds/86.4); if (beat > 1000) beat -= 1000; if (beat < 0) beat += 1000; if ((String(beat)).length == 1) beat = "00"+beat; if ((String(beat)).length == 2) beat = "0"+beat; return beat; }, g: function(){ return jsdate.getHours() % 12 || 12; }, G: function(){ return jsdate.getHours(); }, h: function(){ return pad(f.g(), 2); }, H: function(){ return pad(jsdate.getHours(), 2); }, i: function(){ return pad(jsdate.getMinutes(), 2); }, s: function(){ return pad(jsdate.getSeconds(), 2); }, //u not supported yet // Timezone //e not supported yet //I not supported yet O: function(){ var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4); if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t; return t; }, P: function(){ var O = f.O(); return (O.substr(0, 3) + ":" + O.substr(3, 2)); }, //T not supported yet //Z not supported yet // Full Date/Time c: function(){ return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P(); }, //r not supported yet U: function(){ return Math.round(jsdate.getTime()/1000); } }; return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){ if( t!=s ){ // escaped ret = s; } else if( f[s] ){ // a date function exists ret = f[s](); } else{ // nothing special ret = s; } return ret; }); }// }}} // {{{ mktime function mktime() { // Get Unix timestamp for a date // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_mktime/ // + version: 805.2118 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: baris ozdil // + input by: gabriel paderni // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: FGFEmperor // + input by: Yannoo // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: mktime( 14, 10, 2, 2, 1, 2008 ); // * returns 1: 1201871402 var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length; d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972); var dateManip = { 0: function(tt){ return d.setHours(tt); }, 1: function(tt){ return d.setMinutes(tt); }, 2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; }, 3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; }, 4: function(tt){ return d.setDate(tt+mb); }, 5: function(tt){ return d.setYear(tt+ma); } }; for( i = 0; i < argc; i++ ){ no = parseInt(argv[i]*1); if(no && isNaN(no)){ return false; } else if(no){ // arg is number, let's manipulate date object if(!dateManip[i](no)){ // failed return false; } } } return Math.floor(d.getTime()/1000); }// }}} // {{{ basename function basename(path, suffix) { // Returns filename component of path // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_basename/ // + version: 804.1712 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Ash Searle (http://hexmen.com/blog/) // + improved by: Lincoln Ramsay // + improved by: djmix // * example 1: basename('/www/site/home.htm', '.htm'); // * returns 1: 'home' var b = path.replace(/^.*[\/\\]/g, ''); if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) { b = b.substr(0, b.length-suffix.length); } return b; }// }}} // {{{ dirname function dirname(path) { // Returns directory name component of path // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_dirname/ // + version: 804.2817 // + original by: Ozh // + improved by: XoraX (http://www.xorax.info) // * example 1: dirname('/etc/passwd'); // * returns 1: '/etc' // * example 2: dirname('c:/Temp/x'); // * returns 2: 'c:/Temp' // * example 3: dirname('/dir/test/'); // * returns 3: '/dir' return path.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, ''); }// }}} // {{{ file function file( url ) { // Reads entire file into an array // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_file/ // + version: 804.1712 // + original by: Legaev Andrey // % note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain. // * example 1: file('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm'); // * returns 1: {0: '123'} var req = null; try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { req = new XMLHttpRequest(); } catch(e) {} } } if (req == null) throw new Error('XMLHttpRequest not supported'); req.open("GET", url, false); req.send(null); return req.responseText.split('\n'); }// }}} // {{{ file_get_contents function file_get_contents( url ) { // Reads entire file into a string // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_file_get_contents/ // + version: 804.1712 // + original by: Legaev Andrey // % note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain. // * example 1: file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm'); // * returns 1: '123' var req = null; try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { req = new XMLHttpRequest(); } catch(e) {} } } if (req == null) throw new Error('XMLHttpRequest not supported'); req.open("GET", url, false); req.send(null); return req.responseText; }// }}} // {{{ call_user_func_array function call_user_func_array( strFunctionName , arrParam ){ // Call a user function given with an array of parameters // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_call_user_func_array/ // + version: 804.1712 // + original by: Thiago Mata (http://thiagomata.blog.com) // * example 1: call_user_func_array('isNaN', ['a']); // * returns 1: true // * example 2: call_user_func_array('isNaN', [1]); // * returns 2: false var strCommand = ""; var i; strCommand += "return " + strFunctionName + "("; for( i = 0; i < arrParam.length; ++i ) { strCommand += "arrParam[" + i + "]" ; if( ( i + 1 ) != arrParam.length ) { strCommand += ","; } } strCommand += ")"; var oFunction = new Function( "arrParam" , strCommand ); return oFunction( arrParam ); }// }}} // {{{ function_exists function function_exists( function_name ) { // Return TRUE if the given function has been defined // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_function_exists/ // + version: 804.1712 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Steve Clay // + improved by: Legaev Andrey // * example 1: function_exists('isFinite'); // * returns 1: true if (typeof function_name == 'string'){ return (typeof window[function_name] == 'function'); } else{ return (function_name instanceof Function); } }// }}} // {{{ get_included_files function get_included_files() { // Returns an array with the names of included or required files // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_get_included_files/ // + version: 804.1712 // + original by: Michael White (http://crestidg.com) // * example 1: get_included_files(); // * returns 1: ['http://kevin.vanzonneveld.net/pj_tester.php'] var cur_file = {}; cur_file[window.location.href] = 1; if(!this.__php_js) this.__php_js = {}; if(!this.__php_js.includes) this.__php_js.includes = cur_file; var includes = new Array(); var i = 0; for(var key in this.__php_js.includes){ includes[i] = key; i++; } return includes; }// }}} // {{{ include function include( filename ) { // The include() statement includes and evaluates the specified file. // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_include/ // + version: 804.1808 // + original by: mdsjack (http://www.mdsjack.bo.it) // + improved by: Legaev Andrey // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Michael White (http://crestidg.com) // % note 1: Force Javascript execution to pause until the file is loaded. Usually causes failure if the file never loads. ( Use sparingly! ) // * example 1: include('/pj_test_supportfile_2.js'); // * returns 1: 1 var js = document.createElement('script'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', filename); js.setAttribute('defer', 'defer'); document.getElementsByTagName('HEAD')[0].appendChild(js); // save include state for reference by include_once var cur_file = {}; cur_file[window.location.href] = 1; if (!window.php_js) window.php_js = {}; if (!window.php_js.includes) window.php_js.includes = cur_file; if (!window.php_js.includes[filename]) { window.php_js.includes[filename] = 1; } else { window.php_js.includes[filename]++; } return window.php_js.includes[filename]; }// }}} // {{{ include_once function include_once( filename ) { // The include_once() statement includes and evaluates the specified file during // the execution of the script. This is a behavior similar to the include() // statement, with the only difference being that if the code from a file has // already been included, it will not be included again. As the name suggests, it // will be included just once. // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_include_once/ // + version: 804.1712 // + original by: Legaev Andrey // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Michael White (http://crestidg.com) // - depends on: include // * example 1: include_once('/pj_test_supportfile_2.js'); // * returns 1: true var cur_file = {}; cur_file[window.location.href] = 1; if (!window.php_js) window.php_js = {}; if (!window.php_js.includes) window.php_js.includes = cur_file; if (!window.php_js.includes[filename]) { if(include(filename)){ return true; } } else{ return true; } }// }}} // {{{ require function require( filename ) { // The require() statement includes and evaluates the specific file. // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_require/ // + version: 804.1808 // + original by: Michael White (http://crestidg.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // % note 1: Force Javascript execution to pause until the file is loaded. Usually causes failure if the file never loads. ( Use sparingly! ) // - depends on: file_get_contents // * example 1: require('/pj_test_supportfile_2.js'); // * returns 1: 2 var js_code = file_get_contents(filename); var script_block = document.createElement('script'); script_block.type = 'text/javascript'; var client_pc = navigator.userAgent.toLowerCase(); if((client_pc.indexOf("msie") != -1) && (client_pc.indexOf("opera") == -1)) { script_block.text = js_code; } else { script_block.appendChild(document.createTextNode(js_code)); } if(typeof(script_block) != "undefined") { document.getElementsByTagName("head")[0].appendChild(script_block); // save include state for reference by include_once and require_once() var cur_file = {}; cur_file[window.location.href] = 1; if (!window.php_js) window.php_js = {}; if (!window.php_js.includes) window.php_js.includes = cur_file; if (!window.php_js.includes[filename]) { window.php_js.includes[filename] = 1; } else { // Use += 1 because ++ waits until AFTER the original value is returned to increment the value. return window.php_js.includes[filename] += 1; } } }// }}} // {{{ require_once function require_once(filename) { // The require_once() statement includes and evaluates the specified file during // the execution of the script. This is a behavior similar to the require() // statement, with the only difference being that if the code from a file has // already been included, it will not be included again. See the documentation for // require() for more information on how this statement works. // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_require_once/ // + version: 804.1712 // + original by: Michael White (http://crestidg.com) // - depends on: require // * example 1: require_once('/pj_test_supportfile_2.js'); // * returns 1: true var cur_file = {}; cur_file[window.location.href] = 1; // save include state for reference by include_once and require_once() if (!window.php_js) window.php_js = {}; if (!window.php_js.includes) window.php_js.includes = cur_file; if (!window.php_js.includes[filename]) { if(require(filename)){ return true; } } else { return true; } }// }}} // {{{ abs function abs( mixed_number ) { // Absolute value // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_abs/ // + version: 804.1712 // + original by: _argos // + improved by: Karol Kowalski // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // * example 1: abs(4.2); // * returns 1: 4.2 // * example 2: abs(-4.2); // * returns 2: 4.2 // * example 3: abs(-5); // * returns 3: 5 // * example 4: abs('_argos'); // * returns 4: 0 return Math.abs(mixed_number) || 0; }// }}} // {{{ rand function rand( min, max ) { // Generate a random integer // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_rand/ // + version: 804.1712 // + original by: Leslie Hoare // * example 1: rand(1, 1); // * returns 1: 1 if( max ) { return Math.floor(Math.random() * (max - min + 1)) + min; } else { return Math.floor(Math.random() * (min + 1)); } }// }}} // {{{ round function round ( val, precision ) { // Rounds a float // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_round/ // + version: 804.1712 // + original by: Philip Peterson // * example 1: round(1241757, -3); // * returns 1: 1242000 // * example 2: round(3.6); // * returns 2: 4 var precision = (round.arguments.length > 1) ? round.arguments[1] : 0; return Math.round(val * Math.pow(10, precision))/Math.pow(10, precision); }// }}} // {{{ defined function defined( constant_name ) { // Checks whether a given named constant exists // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_defined/ // + version: 804.1712 // + original by: _argos // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: defined('IMAGINARY_CONSTANT1'); // * returns 1: false return (typeof window[constant_name] !== 'undefined'); }// }}} // {{{ ip2long function ip2long ( ip_address ) { // Converts a string containing an (IPv4) Internet Protocol dotted address into a // proper address // // + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_ip2long/ // + version: 804.1712 // + original by: _argos // * example 1: ip2long( '192.0.34.166' ); // * returns 1: 3221234342 var output = false; if ( ip_address.match ( /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ ) ) { var parts = ip_address.split ( '.' ); var output = 0; output = ( parts [ 0 ] * Math.pow ( 256, 3 ) ) + ( parts [ 1 ] * Math.pow ( 256, 2 ) ) + ( parts [ 2 ] * Math.pow ( 256, 1 ) ) + ( parts [ 3 ] * Math.pow ( 256, 0 ) ); } return output; }// }}}

Adres: http://kevin.vanzonneveld.net/code/php_equivalents/php.js

Görüntülenme: 256 | 4/5 : 5

Yorumlar RSS

++ Yorum Ekle

©