Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: pushing to an array that may or may not exist

I want to create an array with a message.

$myArray = array('my message');

But using this code, myArray will get overwritten if it already existed.

If I use array_push, it has to already exist.

$myArray = array(); // <-- has to be declared first.
array_push($myArray, 'my message');

Otherwise, it will bink.

Is there a way to make the second example above work, without first clearing $myArray = array();?

like image 320
Corey Avatar asked Dec 08 '08 21:12

Corey


People also ask

How do you avoid adding to an array if element already exists?

To push an element in an array if it doesn't exist, use the includes() method to check if the value exists in the array, and push the element if it's not already present. The includes() method returns true if the element is contained in the array and false otherwise. Copied!

What is array push 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).

What is difference between array push and pop in PHP?

Array push is used to add value in the array and Array pop is used to remove value from the array.


1 Answers

Here:

$myArray[] = 'my message';

$myArray have to be an array or not set. If it holds a value which is a string, integer or object that doesn't implement arrayaccess, it will fail.

like image 68
OIS Avatar answered Oct 17 '22 10:10

OIS