开发者

is_array() distinction

开发者 https://www.devze.com 2023-03-11 13:26 出处:网络
I have a piece of code where a variable can either be an array or just a string.开发者_C百科 if(!is_array($relation[\'display_name\']))

I have a piece of code where a variable can either be an array or just a string.开发者_C百科

if(!is_array($relation['display_name']))
{
    // do something with $relation['display_name']
}
else
{
    foreach($relation['display_name'] as $display_name)
    {
        // do the same with $display_name
    }
}

This of course works - but it's not very nice. And I would have to do it a lot of times. Is there a better way of doing this?


You can do it like this:

foreach((array)$relation['display_name'] as $display_name) {
     // do something with $display_name
}


You could do something like this:

if(!is_array($relation['display_name'])) {
    $relation['display_name'] = array($relation['display_name']);
}

# do your foreach here


I would advice you look into fixing the source of the problem.

Why is $relation['display_name'] sometimes an array and sometimes not?

Problem fixing is better then patching the outcome.

That being said, I would create the following:

function transformToArray($mValue) {
    return (is_array($mValue)) ? $mValue : array($mValue);
}


You could write it much shorter with the ternary operator:

foreach ((is_array($a) ? $a : array($a)) as $val) {
  ...
}


I think this is not a bad way of handling this issue. Most of the PHP code I have seen handles stuff like this similar.


If using >= PHP 5.3 you could try something like this. It will run the code on the element if it is singular or implicitly over all array members if an array.

function call($element, $func) {
    if (is_array($element)) {
       foreach($element as $value) {
           $func($value);
       }
    } else {
       $func($element);
    }
}

call($relation['display_name'], function($display_name) {
   // Anything you wanna.
});

CodePad.

0

精彩评论

暂无评论...
验证码 换一张
取 消