Reputation: 22820
So, here's my situation :
I'm getting some input stored in a variable ($keywords
).
This variable may either be a string (=1 keyword) - like "banana"
, or it may be an array (=multiple keywords) - like array ("banana","apple","mango")
.
This is the way I'm using it :
foreach ($keywords as $keyword)
{
// do sth with $keyword
}
This works fine when $keyword
is an array, but when it's not I'm getting errors. (quite obviously)
What would be the most efficient workaround, to avoid errors, while keeping my foreach
structure as-is?
This is what I've thought of (to put before the loop), but I don't really like it :
if (count($keywords)==1) $keywords = array($keywords);
UPDATE : Guys, I know about is_array
. My point was to do it as elegantly as possible, without adding block of code or creating a mess with switch
or if
/else
statements, etc.
Upvotes: 3
Views: 146
Reputation: 21452
simply cast the variable to array:
$keywords = (array) $keywords;
if the variable is an array no thing will happen , otherwise it will be transformed to an array :
so
1
will be array(1)
AND
'keyword'
will be array('keyword')
Upvotes: 6
Reputation: 1258
$type = gettype($keywords);
switch ($type)
{
case "string":
// do what you need with string
break;
case "array":
foreach ($keywords as $keyword)
{
// do smth when is array
}
break;
}
Check for type, my solution allows You to check wether is string, array or other type, which You may specify if needed.
In simplier solution, use if (is_array($keywords);
Upvotes: 0
Reputation: 1573
use the php is_array built-in function
if(is_array($keywords))
foreach ($keywords as $keyword)
{
// do sth with $keyword
}
Upvotes: 0
Reputation: 1078
Just use the is_array command: http://php.net/manual/en/function.is-array.php
Upvotes: 0
Reputation: 1057
if (isset($keywords) && !is_array($keywords)) { $keywords = Array($keywords); }
else if (!isset($keywords)) { $keywords = Array(); }
Upvotes: 0