Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Trim every element in an object and if empty, set to N/A

I have an object:

stdClass Object
(
    [Color] => Red
    [Shape] => Round
    [Taste] => Sweet
)

I want to trim each of the elements in the object and if that element is empty, set it to 'N/A'

So this object:

stdClass Object
(
    [Color] => Red
    [Shape] => 
    [Taste] => Sweet
)

Would become this:

stdClass Object
(
    [Color] => Red
    [Shape] => N/A
    [Taste] => Sweet
)

How should I accomplish this, array_walk maybe?

like image 745
k00k Avatar asked Aug 04 '10 13:08

k00k


1 Answers

Here is a more sophisticated (and slower) one that would allow you to iterate over all properties of an object, regardless of Visibility. This requires PHP5.3:

function object_walk($object, $callback) {

    $reflector = new ReflectionObject($object);
    foreach($reflector->getProperties() as $prop) {
        $prop->setAccessible(TRUE);
        $prop->setValue($object, call_user_func_array(
            $callback, array($prop->getValue($object))));
    }
    return $object;
}

But there is no need to use this if all your object properties are public.

like image 135
Gordon Avatar answered Oct 23 '22 04:10

Gordon