Ankit
Ankit

Reputation: 115

How to trim object properties in PHP?

I have an object $obj as

$obj->{' Property1'} = " value1";
$obj->{'Property2 '} = "value2 ";

I want to get this object $obj as

$obj->{'Property1'} = "value1";
$obj->{'Property2'} = "value2";

I am able to trim all the 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 a solution. Thanks in advance.

Upvotes: 1

Views: 2375

Answers (3)

Dmitry Umarov
Dmitry Umarov

Reputation: 476

A little comment to Daan's answer. In his case script will fall into infinite loop if $obj have more than one property. So a working code looks like this.

<?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);

Upvotes: 1

Daan
Daan

Reputation: 12246

You can't reference a key.

What you have to do is unset it, and set the trimmed version like this:

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

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

var_dump($obj);

Upvotes: 1

KhorneHoly
KhorneHoly

Reputation: 4766

Because you're trying to trim the property of the object. You can't do that.

That would work for an array, but not for an object. If you need to alter the properties of an object you need to change the properties of the class.

Upvotes: -1

Related Questions