0

I have an array thusly

$main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

]

I use a foreach to echo some HTML based on the value of tag. Something like this

    foreach($main_array as $key => $array) {        
        if ($array['tag'] == "bright") { 
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }

This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:

    foreach($main_array as $key => $array) {        
        if ($array['tag'] == "wavy") { 
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }

Should output "james" and "helen". What kind of function do I need to achieve the desired result?

2 Answers 2

2

When checking an item in a list of items, you can use explode() to split it into parts (I've used split by ", " as each item seems to have a space as well) and then use in_array() to check if it is in the list...

if (in_array("bright", explode( ", ", $array['tag']))) {
Sign up to request clarification or add additional context in comments.

2 Comments

yes, this is the right answer. heavy day at work, this was the answer I wanted to give too
Yes, that's it. I was reading about explode but I'm just a hobbyist and still learning. I think I was close with other trial and error but maybe got the syntax a little wrong. Thank you for the explanation.
-1

You cant do it directly, because it return key with values in string. Below are the working code.

<?php
   $main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

];

foreach($main_array as $key => $array) { 
    $str_arr = explode (", ", $array['tag']);
    foreach ($str_arr as $key2 => $array2) {
        if ($array2 == "wavy") { 
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.