Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array vs Php Array

I have two versions of a identical code block in php and javascript. Output of them is slightly different. There are two "undefined" elements in Javascript output. I know that the Javascript Array indexes are incremental which starts from 0 and don't allows us to skip any index number.

Is there anyway to solve this so the Javascript Array output looks like the Php Array output?

Php Code:

$n = array();
$n[0] = 'Apple';
$n[3] = 'Apple';
echo "<pre>";
print_r( $n );
echo "</pre>";

Output:

Array
(
    [0] => Apple
    [3] => Apple
)

Javascript Code:

var n = new Array();
n[0] = 'Apple';
n[3] = 'Apple';
n;

Output:

[
    "Apple", 
    undefined, 
    undefined, 
    "Apple"
]

Thanks!!

like image 560
elegant-user Avatar asked Aug 20 '15 05:08

elegant-user


People also ask

Can I use PHP array in JavaScript?

You can use PHP array in JavaScript. It works for the single as well as the multidimensional array. Use the json_encode() method to achieve this.

Are JavaScript arrays really arrays?

Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays.

What is an PHP array?

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

What is array of array in PHP?

An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values. To create an array in PHP, we use the array function array( ) . By default, an array of any variable starts with the 0 index.


1 Answers

PHP Arrays are Hash Tables, Javascript Arrays are indexed lists

Short Answer

No. There is no way to make Javascript arrays behave like Php arrays without violating ECMA standards (which would mean it's technically no longer javascript).

Yes. But only by replacing the built-in Array prototype behaviors.

See ECMA-262 Section 15.4 Array Objects

What is an array anyway?

Arrays are ordered data and nothing more. While arrays do have an index, the concept of an array "index" shouldn't be conflated with the concept of labeled data storage. Array indices are always sequential, because it points to a position in the array, similar to positions of people in a line.

You couldn't make a line of people with one person first, and one person fourth, and no one else in line. n[0] = 'first'; n[3] = 'fourth;

This is how arrays are defined in nearly every programming language, because it is how the data is stored in memory.

Use Objects Instead

This is the same answer many others have already given to this question. Ultimately a javascript Array is just a predefined type of object, built to behave as outlined above. Thus, the behavior you are trying to change, is actually a behavior that has been carefully engineered.

So, instead of using the special "Array" object, use string keys (as object named properties) and your whole problem is simplified.

Note: this is essentially what the other 'Use an object' answers here are doing, with one notable exception.

n['0'] = 'Apple';
n['3'] = 'Apple';

// OR

n = {
    '0': 'Apple',
    '3': 'Apple',
};

// numeric keys are possible, IFF the var is first explicitly defined as an object.
n = {};
n[0] = 'Apple';
n[3] = 'Apple';

Object isn't enough, it must be an Array? Roll your own "Array" container object.

The drawback here is that you'll need to manually define all the method calls you would like to pass to the array object itself.

var PhpArray = function(ary){
    if (ary instanceof Array) {
        this.ary = ary;
    } else {
        this.ary = new Array(ary);
    }
};

PhpArray.prototype.forEach = function(f){
    for(i in this.ary){
        if (this.ary[i] !== undefined && this.ary[i] !== null) {
            f(i, this.ary[i]);
        }
    }
};

PhpArray.prototype.toString = function(){
    var strResult '';
    this.forEach(function(k, val){
        switch(typeof val) {
            case 'boolean':
            case 'string':
            case 'number':
                strResult += k + ': ' + val;
                break;
            default:
                if (val.toString) {
                    strResult += k + ': ' + val.toString();
                } else {
                    strResult += k + ': ' + typeof val;
                }
        }
    });
};

// Usage:
var n = Array();
n[0] = 'Apple';
n[3] = 'Apple';
var x = new PhpArray(n);
console.log('' + x);

x.ary[5] = 'Pear';

Still not good enough? "Change the Array Behavior!?" you say?

Want to access x[3] = 'Apple'; from the example above?

Or perhaps you really want to override the built-in Array prototype?

Well buckle your seatbelt Dorothy, because javascript is going bye-bye. That's right, we're going somewhere over the ECMA where you can do whatever you want. Sure, other developers will hate you, and third party tools (jQuery) won't work anymore, but at least you'll have your javascript Arrays that aren't arrays.

Unfortunately, I'm not going to help you do that.

like image 55
Tony Chiboucas Avatar answered Oct 24 '22 09:10

Tony Chiboucas