Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><sub>I don't like to beat a dead horse, but still, I'll weigh in here.</sub></p> <p>I wouldn't consider it an anti-pattern; as @Merijn points out, many native PHP functions accept mixed type parameters. Furthermore, many circumstances as your own, require that for succinctness the function accept an element, or a collection, of a given type instead of splitting it over two functions.</p> <p>Casting to <code>(array)</code> is a quick and easy way to achieve this functionality:</p> <pre><code>function printStuff($stuff) { foreach((array) $stuff as $key =&gt; $value) { echo sprintf('%d : %s', $key, $value) . PHP_EOL; } } printStuff("foo"); // 0 : foo printStuff(array("foo", "bar", "qux")); // 0 : foo // 1 : bar // 2 : qux </code></pre> <p>Using <code>$foo = (array) $foo;</code> is better<sup>1</sup> than <code>$foo = array($foo);</code> as when <code>$foo</code> is already an array, it won't wrap it again. </p> <hr> <p>Reference</p> <ul> <li><a href="http://php.net/manual/en/language.types.type-juggling.php" rel="nofollow">http://php.net/manual/en/language.types.type-juggling.php</a></li> <li><a href="http://www.php.net/manual/en/language.types.array.php#language.types.array.casting" rel="nofollow">http://www.php.net/manual/en/language.types.array.php#language.types.array.casting</a></li> </ul> <hr> <p><em><sup>1</sup> Produces the desired results with scalars; objects produce different results. Objects cast to array will enumerate the properties, so use discretion.</em> </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload