Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add elements to an empty array in PHP?

If I define an array in PHP such as (I don't define its size):

$cart = array(); 

Do I simply add elements to it using the following?

$cart[] = 13; $cart[] = "foo"; $cart[] = obj; 

Don't arrays in PHP have an add method, for example, cart.add(13)?

like image 468
AquinasTub Avatar asked Mar 24 '09 09:03

AquinasTub


People also ask

How do you add values to an empty array?

Answer: Use the array_push() Function You can simply use the array_push() function to add new elements or values to an empty PHP array.

Can you add to an array in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

How do you create an empty associative array in PHP?

Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.

Is empty array in PHP?

An empty array is falsey in PHP, so you don't even need to use empty() as others have suggested. PHP's empty() determines if a variable doesn't exist or has a falsey value (like array() , 0 , null , false , etc).


1 Answers

Both array_push and the method you described will work.

$cart = array(); $cart[] = 13; $cart[] = 14; // etc  //Above is correct. but below one is for further understanding $cart = array(); for($i=0;$i<=5;$i++){     $cart[] = $i;   } echo "<pre>"; print_r($cart); echo "</pre>"; 

Is the same as:

<?php $cart = array(); array_push($cart, 13); array_push($cart, 14);  // Or  $cart = array(); array_push($cart, 13, 14); ?> 
like image 124
Bart S. Avatar answered Sep 18 '22 19:09

Bart S.