ParaChase
ParaChase

Reputation: 319

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);

Upvotes: 11

Views: 3645

Answers (5)

Wern Ancheta
Wern Ancheta

Reputation: 23317

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?

Upvotes: 1

Petah
Petah

Reputation: 46060

Also note there is SplFixedArray for fixed sized arrays

$array = new SplFixedArray(5);

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

Upvotes: 7

nickb
nickb

Reputation: 59709

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.

Upvotes: 16

ThiefMaster
ThiefMaster

Reputation: 318588

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.

Upvotes: 5

John V.
John V.

Reputation: 4670

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.

Upvotes: 1

Related Questions