BrittB BrittB - 4 months ago 8
PHP Question

How to compare two values in one associate array in PHP

I am trying to compare two prices within an associative array. I need to pull both prices out so that I can make a calculation. The array I have is:

[10] => Array
(
[A Is For Annabelle 681 2 (fat Quarter)] => 2.8500
[A Is For Annabelle 681 2 (yardage)] => 7.9500
)


And the code i'm trying is:

$fqPrice;
$ydPrice;

foreach ($value as $key => $value) {

if (strpos($key, 'yd') !== false || strpos($key, 'yardage') !== false ) {
$ydPrice = $value;
}

if (strpos($key, 'fq') !== false || strpos($key, 'fat quarter') !== false ) {
$fqPrice = $value;
}
}


It gets to the first if statement but doesn't execute the second one.

Answer

adding the extra array dimension loop (you probably already have this), i changed to a preg_match which is 'cleaner':

<?php
$value = array(10=>array('A Is For Annabelle 681 2 (fat Quarter)'=>'2.8500','A Is For Annabelle 681 2 (yardage)'=>'7.9500'));

$ydPrice=$fqPrice='';


foreach ($value as $first){

    foreach ($first as $key=>$value){


        if (preg_match('#yd|yardage#',$key)){
            $ydPrice = $value;
        }

        if (preg_match('#fq|fat Quarter#',$key)){
            $fqPrice = $value;
        }
    }
}

echo 'y=' . $ydPrice;
echo 'f=' . $fqPrice;
?>

demo: http://ideone.com/JTJNWx

if your only interest in $value[10], you can just use foreach($value[10] as $key=>$value){}