views:

156

answers:

3

Does anybody have an idea why following array() is passing into function. I am not able to understand the array() function. I know, if $_POST dont have any value, it will pass array(). but what are the value in array()?

SomeFunction($_POST ? $_POST : array());
+3  A: 

array() isn't a function per se, it's a language construct. but simply using array() will create an empty array for you i.e. with zero elements.

you probably want to check for:

isset($_POST) ? $_POST : array()

edit:

as pointed out by greg, $_POST will always be set. so there is no need to check for it and return an empty array. someFunc($_POST) should do exactly the same thing

knittl
$_POST should always be set unless you're in an ancient PHP, in which case there are better things to do than pretend there was no POST data.
Greg
yes, you're right. haven't thought of that. but that means that this question is totally ridiculous, because an empty $_POST will be at least an empty array
knittl
I think you mean:empty($_POST) ? array() : $_POST
Josh
@Josh: The result is the same. $_POST is always set, and if it doesn't contain any variables it'll be an empty array. So the whole test is unnecessary.
PatrikAkerstrand
@Machine, yes, I just realized that and posted a comment to that effect. This code is somewhat flawed :-)
Josh
A: 

It's just passing in an empty array if $_POST doesn't evaluate to true.
Why, I don't know...

Greg
My question is that, what that empty array conatian? Does that contain zero value..?
Syed Tayyab Ali
An empty array doesn't contain anything.
Greg
@Syed, the function SomeFunction() expects an array and the code you provided is a (poor) attempt at ensuring that an array is passed to SomeFunction() -- either $_POST, or an empty array
Josh
+7  A: 

array() is not a function, it's a language construct to create a new array. If no arguments (excuse the function terminology) are given, an empty array is created. The difference between PHP arrays and say... Java arrays are that PHP arrays are dynamically resized as new elements are added. But the array()-construct also takes parameters as a comma-separated list of key=>value-pairs.

So, you can create arrays in the following ways:

$empty = array();
$autoIndexed = array (1, 2, 3);
$associative = array('key1' => 1, 'key2' => 2);

var_dump($empty, $autoIndexed, $associative);

// Prints:
Array ()
Array (
   [0] => 1
   [1] => 2
   [2] => 3
)
Array (
   [key1] => 1
   [key2] => 2
)
PatrikAkerstrand