简体   繁体   中英

Is there a PHP equivalent of “new Array (number)” in javascript?

I was trying to convert basic Javascript function into PHP, and I saw that one of the variables was declared var Variable = new Array (13) .

I know that PHP variables are declared like: $variable = array()

but what about the "13" in new Array(13) ? does that translate to $variable = array(13) ? I've tried that but it didn't seem to work.

This in Javascript

var results = new Array (13);

becomes this in PHP, am I correct?

$results = array(13);

Actually, in this context, you're creating an array of size 13 .

You don't really need to preallocate arrays in PHP, but you can do something like:

$result = array_fill( 0, 12, null);

This will create an array with 13 elements (indexes 0 through 12) whose values are null .

Also note there is SplFixedArray for fixed sized arrays

$array = new SplFixedArray(5);

http://php.net/manual/en/class.splfixedarray.php

new Array(someNumber) in JS creates an array containing someNumber elements which are undefined . Unless you want that you should always use [...] to create an array with some elements since that syntax is not ambiguous while new Array() works differently depending on the number and type of arguments.

array(13) in PHP however creates an array containing a single value 13 .

A roughly similar function in PHP is array_fill(0, 12, null) . However, PHP might allocate an empty array and then grow it while filling it.

No, putting a number inside the parenthesis in PHP adds one value to the array that is the int 13. Whereas a number in JS inside the parenthesis makes an array with that number of undefined values.

Arrays in PHP are dynamic, you don't need to declare their size like you sometimes do in JS.

This creates an array with 13 undefined values:

var results = new Array (13);

This creates an array with the first index (index 0) equal to 13:

$results = array(13);

So that's incorrect. If you want the same result as that of javascript you'd like something like this:

$results = array_fill(0, 13, '');

You might also want to check out this question:

How to create an empty array in PHP with predefined size?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM