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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With