Luka Boras
Luka Boras

Reputation: 11

if clause not working as it should

I have a problem. I have wrote code that needs to point out the elements of array which are bigger that the next element of array. You can see on the output picture that array $arr should contain only element 70 because $ar[294]=70 > $ar[295]=69. But code is somehow putting more elements to $arr which do not satisfly if statement ($ar[$i]>$ar[$i+1]).

How is this possible?

$ar = array();
for ($i=0; $i < sizeof($retcikonacno); $i++) {
    if ($retcikonacno[$i]["n2"] >= 1001 && $retcikonacno[$i]["n2"] <= 1013) {
        array_push($ar, $retcikonacno[$i]["vpont"]);
    }   
}

echo "ar=";
echo "</br>";
print_r($ar);

echo "</br>";
echo "-------------------";
echo "</br>";
echo "-------------------";

echo "</br>" . "</br>";

$arr = array();

$size = sizeof($ar)-1;
for ($i=0; $i < $size; $i++) {
    if ($ar[$i] > $ar[$i+1]) {
        array_push($arr, $ar[$i]);
    }
}

echo "arr=";
echo "</br>";
print_r($arr);

OUTPUT:

[Output

Upvotes: 0

Views: 46

Answers (1)

Luka Boras
Luka Boras

Reputation: 11

I was consulting with my mentor and he solved this problem.

He said that it is possible that php (mistakenly and for unknown reason) read memory location of $ar[$i] and $ar[$i+1] and not the actual value of an array. So if clause was not valid.

SOLUTION: Instead of creating array $ar as I did with array_push($ar, $retcikonacno[$i]["vpont"]), he used function intval, so it was array_push($ar, intval($retcikonacno[$i]["vpont"])). This created array of correct values and if clase was doing good.

Upvotes: 1

Related Questions