{'Property2 '} = "value2 "; I want...">

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.

+1
source share
3 answers

You cannot refer to a key.

What you need to do is disable it and install the cropped version as follows:

<?php
$obj = new stdClass;
$obj->{' Property1'} = " value1";

foreach($obj as $prop => $val)
{
     unset($obj->{$prop});
     $obj->{trim($prop)} = trim($val);
}

var_dump($obj);
+1
source

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);
+1
source

. .

, . , .

0

All Articles