Page 1 of 1

test if value is in multidimensional array

Posted: Sun Jan 24, 2010 12:52 am
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

Re: test if value is in multidimensional array

Posted: Sun Jan 24, 2010 4:28 pm
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.

Re: test if value is in multidimensional array

Posted: Mon Jan 25, 2010 1:52 am
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

Re: test if value is in multidimensional array

Posted: Mon Jan 25, 2010 6:45 am
by JakeJ
Looks pretty efficient to me! Just make sure the query behind it only selects the fields you need, it will improve performance.