views:

43

answers:

2

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?

+2  A: 

Let's keep it simple:

$foo = new StdClass;
$foo->prop1 = '   foo   ';
$foo->prop2 = NULL;
$foo->prop3 = 'bar';

foreach($foo as &$prop) {
    $prop = trim($prop);
    if (empty($prop)) {
        $prop = 'N/A';
    }
}

print_r($foo);

And that would give:

stdClass Object
(
    [prop1] => foo
    [prop2] => N/A
    [prop3] => bar
)
Gordon
I hope his objects are actually of type `stdClass`, because if it was just an example, he might have trouble with this approach.
Artefacto
@Artefacto yes, indeed. In lack of further information I am assuming the OP really has `stdClass` objects as shown.
Gordon
The objects in question are indeed of type stdClass
k00k
Worked perfectly, thanks @Gordon!
k00k
@Artefacto added a solution for arbitrary objects below.
Gordon
+1  A: 

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.

Gordon
My point was not only the visibility. The object could also be Traversable. But this solution also addresses that.
Artefacto
@Artefacto may I ask you to have a look at http://stackoverflow.com/questions/3417180/unicode-class-names-bug-or-feature (completely unrelated to this question). Value your expertise on it.
Gordon
@Gordon That's actually a though question that requires some time (and maybe some research). How the script is interpreted depends on whether the zend multibyte option is enabled and even on the locale. The same script may not work in different machines depending on how the lowercasing normalization on class names and function/method names is done. I'll probably answer the question tomorrow, for now I must rest :p
Artefacto
@Artefacto Thanks a lot and no hurry :)
Gordon