BrittB BrittB - 1 year ago 62
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:


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 Source

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

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


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;


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download