What is the right way for doing this?
It gives me an error:
$lingue = array('IT','EN','FR');
$item = new stdClass();
$item->IDCat = 1;
foreach($lingue as $l){
$item->Desc_{$l} = trim(addslashes($_POST['Desc_'.$l]);
}
You would need to wrap the whole expression into the curly quotes: {"Desc_".$l}
However, seeing as the set of languages is going to be dynamic, consider using an Array for this instead:
$item = new STDClass();
$item->Desc = new Array();
foreach($lingue as $l){
$item->Desc[$l] = trim(addslashes($_POST["Desc_$l"]));
}
echo $item->Desc["IT"]; // outputs the italian description
Additional observations:
Note that if you're going to use these values in a database query, addslashes() is not sufficient protection against SQL injection. Use the string escaping function of the SQL library you are using.
Using $_POST["Desc_xyz"] without checking whether it's set will throw a PHP notice, which you want to avoid. Consider adding a check:
if (!empty($_POST["Desc_$l"]))
$item->Desc[$l] = trim(addslashes($_POST["Desc_$l"]));
$item->{"Desc_$l"} and $_POST["Desc_$l"] for short.) after the trim() call... ;-)$lingue = array('IT','EN','FR');
$item = new stdClass();
$item->IDCat = 1;
foreach($lingue as $l){
$item->{'Desc_'.$l} = trim(addslashes($_POST['Desc_'.$l]));
}
The dynamic accessor must be enclosed with curly braces and you'r lacking a ) at the end of the trim() call.
Just to highlight the difference between $item->{'Desc_'.$l} = ... and $item->Desc_{$l} = ...:
//...
foreach($lingue as $l){
$item->{'Desc_'.$l} = trim(addslashes($_POST['Desc_'.$l]));
}
print_r($item);
// outputs:
/*
stdClass Object
(
[IDCat] => 1
[Desc_IT] => a
[Desc_EN] => a
[Desc_FR] => a
)
*/
while
//...
foreach($lingue as $l){
$item->Desc_{$l} = trim(addslashes($_POST['Desc_'.$l]));
}
print_r($item);
// outputs:
/*
stdClass Object
(
[IDCat] => 1
[Desc_] => Array
(
[IT] => a
[EN] => a
[FR] => a
)
)
*/
This is actually the same as
//...
foreach($lingue as $l){
$item->Desc_[$l] = trim(addslashes($_POST['Desc_'.$l]));
}
Seems to be an imprudence in the parser.
)intrim(addslashes($_POST['Desc_'.$l]);