Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using foreach with a variable which may NOT be an array

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.

like image 564
Dr.Kameleon Avatar asked Mar 27 '26 23:03

Dr.Kameleon


1 Answers

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')

like image 187
amd Avatar answered Mar 29 '26 11:03

amd