Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 336
ParaChase Avatar asked Jul 09 '12 22:07

ParaChase


People also ask

What does new array () mean in JavaScript?

The var weekday = new Array( 7 ); is declaring an array with 7 items in it, as shown by the following lines. The array stores values at each index( number ) and you access the values via variable[#] You do not need it in javascript but many other languages such as Java require an explicit value.

Can I use PHP array in JavaScript?

You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function. PHP array can be converted to JavScript array and accessible in JavaScript. Whatever the array type is, a single or multidimensional or indexed or associative array.

What is numerical array in PHP?

Numeric arrays allow us to store multiple values of the same data type in a single variable without having to create separate variables for each value. These values can then be accessed using an index which in case of numeric arrays is always a number. Note: By default the index always starts at zero.

What are the 3 types of PHP arrays?

Create an Array in PHP In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.


Video Answer


2 Answers

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.

like image 90
nickb Avatar answered Nov 15 '22 12:11

nickb


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.

like image 40
ThiefMaster Avatar answered Nov 15 '22 14:11

ThiefMaster