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

627

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';
        }
}
507

Answer

Solution:

You need tounserialize() 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 useisset(), feel free to usearray_key_exists() if you must.

People are also looking for solutions to the problem: javascript - Playing a video stored in server in android WebView

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.