views:

883

answers:

6

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();"?

Thanks.

+15  A: 

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 without arrayaccess it will fail.

OIS
It's weird, but it's true. PHP won't trigger any error/warning/notice on that.
troelskn
Its a feature. :)
OIS
...an incredibly useful feature (for me at least)
da5id
A: 

Check if the array exists first, and if it doesn't, create it...then add the element, knowing that the array will surely be defined before hand :

if (!isset($myArray)) {
    $myArray = array();
}

array_push($myArray, 'my message');
Andreas Grech
snap ... except the new bit, which I don't think works in php
benlumley
heh yea...that's what happens when you have one too many languages roaming in your head :-)
Andreas Grech
A: 
if ($myArray) {
  array_push($myArray, 'my message');
}
else {
  $myArray = array('my message');
}
George Jempty
You should test if a var holds an array with isset and is_array.
OIS
Why *and*? is_array() should be enough. It can hardly be an array if it is not set.
Tomalak
Yes, my bad wording. I meant either. Should have used or.
OIS
A: 

OIS' way will work.

Or

if (!isset($myArray)) 
    $myArray=array();
array_push($myArray, 'message');
benlumley
+2  A: 

You should use is_array(), not isset. Usefull if myArray is being set from a function that returns an array or a string (-1 on error for example)

This will prevent errors if myArray is declared as a not an array somewhere else.

if(is_array($myArray))
{
   array_push($myArray,'my message');
}
else
{
   $myArray = array("my message");
}
Byron Whitlock
You correctly mention is_array, but use non-existent function array_exists.
OIS
Doh! TCL was getting in the way :P
Byron Whitlock
A: 

Okay, so it requires logic. I guess i was hoping to do it all in one line. That's good to know. Thanks!

Corey Maass
It doesn't require is_array if you're smart and keep your functions and methods small. As small as you can make them. Divide and conquer!
OIS