Web Info and IT Lessons Blog...

Friday 5 June 2015

Compare Associative Arrays in PHP

The previous lesson of PHP Lessons Series was about file download in php and in this lesson we will learn to compare and subtract two associative arrays in PHP.

Compare Associative Arrays

Let us say we have two arrays and we want to subtract the matching values of second array from the first array. To do this we need to compare the matching values of both arrays and subtract the second ones from the first ones and store the result in a new array. A php example script is given below:


<?php
$arr1 = array(0=> array('item'=>'English Book','quantity'=>90),
       1=>array('item'=>'Science Book','quantity'=>68),
       2=>array('item'=>'Maths Book','quantity'=>34));
     
$arr2 = array(0=> array('item'=>'Science Book','quantity'=>30),
       1=>array('item'=>'English Book','quantity'=>58));

$newArr = array();
$count = 0;
foreach($arr1 as $firstArray){
      $newArr[$count]['item'] =  $firstArray['item'];
      $newArr[$count]['quantity'] =  $firstArray['quantity'];
      foreach($arr2 as $secondArray){
    if($firstArray['item'] == $secondArray['item']){
       $firstArray['quantity'] = $firstArray['quantity'] - $secondArray['quantity'];
       $newArr[$count]['item'] =  $firstArray['item'];
       $newArr[$count]['quantity'] =  $firstArray['quantity'];
    }
      } 
      $count ++;
}

print_r($newArr);
?>

The above php script contains two arrays $arr1 and $arr2, the values of both arrays are compared in nested foreach loop. If the values of item matches, the quantity of second array is subtracted from the first array and the result is saved in a new array $newArr.

Stay tuned for more lessons...

No comments:

Post a Comment