Does anyone know of any issues, performance or other, that can occur by casting a variable to an array instead checking it first?
// $v could be a array or string
$v = array('1','2','3');
OR
$v = '1';
instead of:
if (is_array($v)) foreach ($v as $value) {/* do this */} else {/* do this */}
I've started to use:
foreach((array) $v as $value) {
// do this
}
It stops the repetition of code quite a bit - but performance is on my mind, not ugly code.
Also, does anyone know how php handles casting an array to an array? No errors are thrown but does the php engine check if it's a array, then return a result before doing the cast process?
The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.
In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
First: Premature optimization is the root of all evil. Never let performance influence your coding style!
Casting to an array allows to some nice tricks, when you need an array, but want to allow a single value
$a = (array) "value"; // => array("value")
Note, that this may lead to some unwanted (or wanted, but different) behaviours
$a = new stdClass;
$a->foo = 'bar';
$a = (array) $a; // => array("foo" => "bar");
However, this one
if(is_array($v)) {
foreach($v as $whatever)
{
/* .. */
}
} else {
/* .. */
}
allows you to decide what should happen for every single type, that can occur. This isn't possible, if you cast it "blindly" to an array.
In short: Just choose the one, that better fits the needs of the situation.
As Felix Kling says above, the best solution is to have your data come from a source that guarantees its type. However, if you can't do that, here's a comparison for 1000000 iterations:
check first: 2.244537115097s
just cast: 1.9428250789642s
(source)
Just casting without checking (using in_array
) seems to be (slightly) quicker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With