Reputation: 16007
I'm trying to port some PHP code over to C#, and I ran across a PHP function of this form:
function DoStuff($myVar, array $myArray1, array $myArray2 = array())
{
// some code not involving $myArray2
if ($myArray2)
{
// do things with $myArray2, but if I arrive here, what
// condition was met?
}
}
My best guess (which may be completely wrong) after looking over a number of appropriate pages in php.net as to what's happening:
$myArray2
is optional, but if nothing is provided the array goes in emptyif
conditional checks to see whether $myArray2
was passed in with one or more elementsIs this correct? If not, what is correct? Thanks!
Upvotes: 2
Views: 60
Reputation: 13298
You are correct and here is an explanation:
The type-hint array
says that $myArray2
can only accept an array. The default value of array()
says that $myArray2
is optional and, if it is not passed, an empty array will be assigned.
Given that the only thing that $myArray2
could be at the time of the if
conditional is an array, you can confirm what will be accepted by type casting to a boolean. In this case, an array is always converted to true unless it has no elements in which case it is false.
Aside: You should be careful to note that whilst it is currently illegal to pass NULL in as a parameter to both $myArray1
and $myArray2
, it is legal to set a default value of $myArray2
as NULL. In that case, you could also pass in NULL to that parameter. Additionally, the conditional would then also be checking that the parameter was not set to NULL.
Upvotes: 2
Reputation: 318548
Yes, this is correct. The function will also throw a fatal error if something that is not an array is passed for $myArray1
or $myArray2
.
Upvotes: 6