Home > OS >  if a key matched in loop print value in php array
if a key matched in loop print value in php array

Time:07-30

Array ( 
[category] => abc
[post_tag] => test
[nav_menu] => Home 
[link_category] => Link 1 
[post_format] => format 
)

print conditional value from a loop in php How can i check if a key is present in this loop

foreach($array as $ar)
{
if($ar->category == 'abc')
{
echo 'found';
}
}

CodePudding user response:

I'm not quite sure what you're trying to find but if it's specific key/value pair it should look like this:

$array = Array ( 
        'category' => 'abc',
        'post_tag' => 'test',
        'nav_menu' => 'Home',
        'link_category' => 'Link 1',
        'post_format' => 'format'
    );

    foreach($array as $key => $value) {
        if ($key === 'category' && $value === 'abc') echo 'found', PHP_EOL;
    }

CodePudding user response:

Here you just have an associated array that doesn't have any nested arrays.

So if you want to do what you want on this array, you should do something like this:

if (isset($array['category']) && $array['category'] === 'abc') {
    echo 'Found!';
}

Using null coalescing operator can make it easier:

if ($array['category'] ?? null === 'abc') {
    echo 'Found!';
}

CodePudding user response:

Your question isn't very clear. Do you want to check if a key on an array exists or check if the value exists inside the foreach? I will try to answer both.

Given that we have this array:

$array = [
'category' => 'abc'
'post_tag' => 'test'
'nav_menu' => 'Home' 
'link_category' => 'Link 1' 
'post_format' => 'format' 
];

If you want to check if a key exists in an array and print the keys value:

if(array_key_exists('category', $array){
  echo $array['category']; // prints abc
}

more info about array_key_exists here: array_key_exists

If you want to check if a value exists in the array:

foreach($array as $ar){
  if($ar === 'abc'){
    echo $ar; // prints abc
  }
}

In case you want to check for both of the above:

if(array_key_exists('category', $array) && $array['category'] === 'abc'){
  echo $array['category']; // prints abc
}

I hope this helps you figure things out.

  •  Tags:  
  • php
  • Related