3

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.

5 Answers 5

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

Fabulously simple; 7 answers (so far) and only you got the very essence of my question. Thanks a lot, buddy!
Gj, deleted my answer for this ;)
Was just writing a similar thing when i saw this, +1.
Yeah, totally beat my (deleted) answer. +1
0
if (isset($keywords) && !is_array($keywords)) { $keywords = Array($keywords); }
else if (!isset($keywords)) { $keywords = Array(); }

Comments

0

Just use the is_array command: http://php.net/manual/en/function.is-array.php

Comments

0

use the php is_array built-in function

if(is_array($keywords))
foreach ($keywords as $keyword)
{
    // do sth with $keyword
}

Comments

0
$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);

1 Comment

OP wants to convert the string to an array to use it in the foreach loop - your solution would break after converting it and make no use of the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.