Botić Denis Botić Denis - 5 months ago 14
PHP Question

PHP Array - foreach - print key value only if that key name exist in current array

I am getting a response from database in array like this:

Array ( [mage_form_post_status] => draft [mage_form_post_type] => post [mage_form_post_permission] => public [mage_form_post_author] => 1 [mage_form_post_redirect] => 0 )
Array ( [mage_form_post_status] => draft [mage_form_post_type] => post [mage_form_post_permission] => public [mage_form_post_author] => 1 [mage_form_post_redirect] => 88 )
Array ( [mage_gym_name] => Fanna - test [mage_your_name] => John )


What I am trying to achieve is to display mage_gym_name value only.
I have succeed to display it with this code:

foreach($gym_titles as $gym_title){

print_r(unserialize($gym_title));
echo '<br><br><br>';

}


Problem is that when there is no result, like in first two arrays I get 3 empty breaklines.

So I believe that I should wrap:

print_r(unserialize($gym_title));
echo '<br><br><br>';


In some kind of condition which should check if that current array contains that key name.

I have tried like this but it doesn't work:

foreach($gym_titles as $gym_title){

if (array_key_exists('mage_gym_name', $gym_title) {
echo "The 'first' element is in the array";

print_r(unserialize($gym_title));
echo '<br><br><br>';

} else {
echo 'no such element in this array';
}
}

Answer

You need to unserialize() before you check for the key:

foreach($gym_titles as $gym_title){

    $result = unserialize($gym_title);

    if(isset($result['mage_gym_name'])) {
        echo "The 'first' element is in the array";
        print_r($result);
        echo '<br><br><br>';
    } else {
        echo 'no such element in this array';
    }
}

I use isset(), feel free to use array_key_exists() if you must.