You can cast a variable to an array by using:
$var = (array)$arr;
Answer from cbroughton on Stack Overflowphp - Cast to array VS is_array() - Stack Overflow
Why does PHP convert integer-string array keys to integer?
Warning: Array to string conversion in Variable method
Using implode() on an array of booleans will cast TRUE to 1 and FALSE to ''
How can I convert an array back into an object in PHP?
Can I convert an object to an array in PHP while maintaining its methods?
Can I use JSON encoding/decoding for all objects when learning how to convert object to array in PHP?
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.