-2

It is my first time coding in PHP. I am trying to return an array which contains of the amount of each type of cash

public function test($a){
    $a = [];
        $cash = array(
            '20'   => 0,
            '30'   => 0,
            '40'   => 0,
            '50'  => 0,
            '60'  => 0,
            '70'  => 0,
            '80' => 0,
        );

        foreach($a as $k => $v) {
            if (array_key_exists("$k",$cash) && $v!= null ) {
                $cash[$k] += 1;
            }
        }

        return  $cash;
    }

When I try testing the code I get the error: Invalid argument supplied for foreach()

Bab
  • 433
  • 5
  • 12

4 Answers4

0

the 1st argument for foreach() must be an array. $a is not an array Also note that you are trying to use $count, which was not previously defined as an array. Either that "$cash" assignment should be "$count" or vice-versa.

Yoshimitsu
  • 370
  • 2
  • 9
0

Try calling with test(array('20' => 0)); and you will not get the error. You are probably calling it with something that is not an array?

0
$cash[$key] += 1;

should be

$cash[$k] += 1;

I have included the code that I used for testing here:-

<?php
function test($a){
  $cash = array(
    '20' => 0,
    '30' => 0,
    '40' => 0,
    '50' => 0,
    '60' => 0,
    '70' => 0,
    '80' => 0,
  );

  foreach($a as $k => $v) {
      if (array_key_exists("$k",$cash) && $v != NULL ) {
        $cash[$k] += 1;
      }
    }
  return  $cash;
}

// code that I have added to test the function from the post question
$testArray = array(
  '20' => 1,
  '30' => 2,
  '40' => 3,
  '50' => 4,
  '60' => 5,
  '70' => 6,
  '80' => 7,
);

$cash = test($testArray);

foreach($cash as $k => $v) {
  echo("\n$k : $v");
}

?>

Results:-

20 : 1
30 : 1
40 : 1
50 : 1
60 : 1
70 : 1
80 : 1
k.mak
  • 1
  • 4
-2

Maybe you can try removing the comma at the end of your array.

change: '80' => 0,

to: '80' => 0

Rafael
  • 7,605
  • 13
  • 31
  • 46
  • Sorry, it's a typo here on Stackoverflow. It's not there in my code – Bab Oct 16 '18 at 23:26
  • 3
    that's actually common practice, to leave the trailing comma. See https://stackoverflow.com/questions/2829581/why-do-php-array-examples-leave-a-trailing-comma – Yoshimitsu Oct 16 '18 at 23:27