0

I have three different arrays. Getting the value from first array and measuring it in second array if match found enter that data into new array, 1st array is types, 2nd array is results and 3rd array is data. Problem occurs when I use $data[$types[$i]]['price'] += $result[$x]['price']; it throws notice error

NOTICE Undefined index: price on line number 28

If I use it in a way like $data[$types[$i]][] = $result[$x]['price'];

this generates new index array but does not plus the price and does not show the Notice as well.

The question is if it does not accept the price as an index then why it accept $data_array[$types[$i]]['name'] name as index in row before it. And I want to plus all the prices and assign it to the key price and of course want to get rid of notice.

$types[] = "class";
$types[] = "late_fine";
$types[] = "exam_fees";

$result[] = array("name"=>"class 1", "type" => "class", "price" => 10 );
$result[] = array("name"=>"class 1", "type" => "class", "price" => 20 );
$result[] = array("name"=>"late fine", "type" => "late_fine", "price" => 50 );
$result[] = array("name"=>"late fine", "type" => "late_fine", "price" => 40 );

$i=0;
$x=0;
while($i < count($types)){
 while($x < count($result)){    
     if($types[$i] == $result[$x]['type']){          
        $data[$types[$i]]['name'] = $result[$x]['name'];
        $data[$types[$i]]['price'] += $result[$x]['price'];          
     }   
    $x++;
     }   
    $x = 0; 
    $i++;
 } 

 echo "<pre>";
 print_r($data);

Index array I talked about above in the text

Array
  (
   [class] => Array
    (
        [name] => class 1
        [0] => 10
        [1] => 10
        [2] => 10
    )
   )

Result I am expecting without Notices

NOTICE Undefined index: price on line number 28
NOTICE Undefined index: price on line number 28

Array
(
   [class] => Array
    (
        [name] => class 1
        [price] => 30
    )

   [late_fine] => Array
    (
        [name] => late fine
        [price] => 90
    )
 )
Mohsin
  • 179
  • 4
  • 13
  • 3
    You __cannot__ add a number to something that __is not defined__. – u_mulder Jul 18 '18 at 14:27
  • 1
    `$foo = 'bar';` doesn’t care if `$foo` already exists at that point or not, it will just be created if necessary. `$foo += 5;` however requires to _read_ the current value of the variable first - to know _what_ those 5 should be added to in the first place. Now this _reading_ can obviously not happen, if `$foo` doesn’t exist already. – CBroe Jul 18 '18 at 14:30
  • hmm very straight and to the point answers. Thanks guys – Mohsin Jul 18 '18 at 15:17

0 Answers0