Chuck K Chuck K - 1 month ago 9
PHP Question

Can I do something like this in PHP?

Started learning using CodeIgniter and I am wondering what the best way is to re-do this loop to compare two variables please...

<?php
$user = array('name' => 'name', 'hasCat'=> 1, 'hasDog' => 0);
$pets = array('hasCat', 'hasDog');
foreach($pets as $pet) {
echo ($pet==$user->hasCat) ? 'checked' : '';
the hasCat ^ is the one I want to replace to $pets??
}
?>

Answer

You can't access the array value by doing $user->hasCat, that implies hasCat is a variable of the object $user. Try this:

 <?php
$user = array('name' => 'name', 'hasCat'=> true, 'hasDog' => false);
$pets = array('hasCat', 'hasDog');
foreach($pets as $pet) {
    if($user[$pet]) echo $pet;
}
?>
Comments