test if value is in multidimensional array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sc0tt
Forum Newbie
Posts: 5
Joined: Sat Jan 23, 2010 1:05 am

test if value is in multidimensional array

Post by sc0tt »

I have a multidimensional array and can't seem to get at the desired value "headline-inline". I know its there. I tried specifying the ['value'] along with the array name; but I got a warning. Here is the code:

Code: Select all

 
<?php
if (in_array("headline-inline", $field_headline_options)) {
   print "Found it"
}
?>
 
And here is the array output:

Code: Select all

 
[field_headline_options] => Array
        (
            [0] => Array
                (
                    [value] => headline-inline
                    [safe] => headline-inline
                    [view] => Inline
                )
 
            [1] => Array
                (
                    [value] => headline-color-black
                    [safe] => headline-color-black
                    [view] => Color: Black
                )
 
            [2] => Array
                (
                    [value] => headline-size-medium
                    [safe] => headline-size-medium
                    [view] => Size: Medium
                )
 
        )
 
Thank you for any help with this,
Scott
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: test if value is in multidimensional array

Post by JakeJ »

Loop through the entire array and when you found the desired value, break out of the array and do what you will with it. Just remember though, if you need the value of that variable, you use to use this:

Code: Select all

$var = null
For each (loop through) {

If ($value = "desired text") {
global $var;
$var = $value;
break;
}
}

Go take a look at a tutorial on looping through an array, they're very easy to find. I'd give you a link, but if you're going to learn php, you're going to have to learn to look stuff up.
sc0tt
Forum Newbie
Posts: 5
Joined: Sat Jan 23, 2010 1:05 am

Re: test if value is in multidimensional array

Post by sc0tt »

Thanks for your help. Not sure if this is the most efficient method; but it worked:

Code: Select all

<?php foreach ($field_headline_options as $value) {
    if ($value['value'] == 'headline-top') { ?>
         echo "found it";
                  break;
    }
         }
?>
Thanks again!
Scott
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: test if value is in multidimensional array

Post by JakeJ »

Looks pretty efficient to me! Just make sure the query behind it only selects the fields you need, it will improve performance.
Post Reply