Is_array () distinction

I have a piece of code where a variable can be either an array or just a string.

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
    }
}

It certainly works - but it's not very nice. And I would have to do this many times. Is there a better way to do this?

+3
source share
6 answers

You can do it as follows:

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

You can do something like this:

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

# do your foreach here
+5
source

.

$relation['display_name'] , ?

, .

:

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

:

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

, . PHP, , , .

0

If you use> = PHP 5.3, you can try something like this. It will run the element code if it is singular or implicit over all elements of the array, if the 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
source

All Articles