Can I cast the PHP foreach value to an object or another?

Can I cast the PHP foreach value to an object or another?

25-01-2022 1467
firstly, let's show an example for our scenario
let's assume that we have a PHP multidimensional associative array $arr which has name and age
<?php
$arr = [
['name' => 'Ahmed', 'age' => 10],
['name' => 'Ali', 'age' => 15],
['name' => 'Gehad', 'age' => 30],
];
?>
now, I try casting each single value as an object insted of array using PHP foreach
<?php
foreach ($arr as (object)$element)
echo"$element->name,$element->age <br>";
?>
that is false, I can't cast the PHP foreach value becuase the expression <?php foreach ($variable as $value) ?> is not writable, it just a declartion.
and now what is the soultion or how can I cast the PHP foreach element?
just
<?php
foreach ($arr as $element) {
$element = (object)$element;
echo"$element->name,$element->age <br>";
}
?>
and by following the previous syntax you can cast the PHP value

 

Also Readers Studied

© Copyright reserved to the channel owners | Terms and Privacy

add to your home screen