Conor Conor - 7 months ago 10
PHP Question

Why Isn't the Value of 0 Being Passed in the foreach Loop?

Trying to test my code before adding it to Production, but why is the foreach loop only passing 3 values to

$strokes
and not all 4
$_POST
array values. One of them being
0
.

Code: https://ideone.com/qBO4rx

$_POST = array("h1" => 1, "h2" => 2, "h3" => 3, "h4" => 0);
$strokes = array();

$strokes_keys = array('h1', 'h2', 'h3', 'h4');

foreach ($strokes_keys as $stroke) {
if ($_POST[$stroke]) {
array_push($strokes, $_POST[$stroke]);
}
}

$counts = count($strokes);

var_dump($strokes);
var_dump($counts);


Results:

Success time: 0.04 memory: 52480 signal:0
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
int(3)

Answer

The array_push($strokes, $_POST[$stroke]); does not execute for last item, because zero equals to false. Maybe you should try:

if (isset($_POST[$stroke])) {
     array_push($strokes, $_POST[$stroke]);
}

instead.