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
Solution:
You need to
unserialize()
before you check for the key:I use
isset()
, feel free to usearray_key_exists()
if you must.