How to trim object properties in PHP?
I have an object $objlike
$obj->{' Property1'} = " value1";
$obj->{'Property2 '} = "value2 ";
I want to get this object $objas
$obj->{'Property1'} = "value1";
$obj->{'Property2'} = "value2";
I can trim all values using
foreach($obj as $prop => &$val)
{
$val = trim($val);
}
but doing this (below), causing an error
foreach($obj as &$prop => &$val)
{
$prop = trim($prop);
$val = trim($val);
}
Please tell me the solution. Thanks in advance.
A small comment to Daan. In his case, the script will end up in an infinite loop if $ obj has more than one property. Thus, the working code is as follows.
<?php
$obj = new stdClass;
$obj->{' Property1'} = " value1";
$obj->{'Property2 '} = "value2 ";
$newObj = new stdClass;
foreach($obj as $prop => $val)
{
$newObj->{trim($prop)} = trim($val);
}
$obj = $newObj;
unset($newObj);
var_dump($obj);