I am stuck with PHP's array()?
-
22-07-2019 - |
Question
Why is the following array()
passed into a function. I am not able to understand the array()
function.
I know if $_POST doesn't have any value, it will pass array()
, but what is the value in array()
?
SomeFunction($_POST ? $_POST : array());
Solution
array()
isn't a function per se, it's a language construct. But simply using array()
will create an empty array for you, that is, 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.
OTHER TIPS
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
)
It's just passing in an empty array if $_POST doesn't evaluate to true
.
Why, I don't know...