0

At the moment i try to create a function in php which simply reads an int value of a field of an array and compares it to a max value.
If this max value is reached, it shall set the value of the field to zero, jump to the next field in the array and increase the int value stored inside.
If this value also reached the max value do the same as above.
If the above condition isn´t true it shall just increase the stored value in the array.

My Code looks like this:

if($sign_counter[0] === (count($pw_signs) - 1)){
    $counter = 0;
    while($sign_counter[$counter] === (count($pw_signs) - 1)){
        $sign_counter[$counter] = "0";
        $counter++;
    }
    $sign_counter[$counter]++;
}
else{
    $sign_counter[0]++;
}

I allready tested this part of the function several times with different values on my website and browser. I also checked if the values were stored correctly in the array and inside needed variables.

Thats how my array looks like:

$sign_counter = array("38", "2");

For example:

$sign_counter array to store int values
(count($pw_signs) - 1) always equals 38 (because there are 39 fields in the counted array)
$counter used to determine the field position inside the array

Now if i store the value "38" in the first field and "2" in the second field of the array the code should detect, that the max value is reached in the first field, set the value of the field to 0, then jump to the next field and increase its value by 1.

Instead of what i want to achieve the code just increases the value of the first field of the array.
It looks like the while loop just ignores it's own condition but the values itself don't seem to be the problem.

I don't really get why the while loop behaves like this.
Do i completly miss something here?

Would appreciate any help.
Greetings Sleepy

2
  • 3
    Your sign counter values are string datatype (with integer values); but you're doing a === (typed) check against an integer value Commented Feb 1, 2017 at 23:48
  • Goddamn, that was easy. Thank you very much, now it works. Probably should concentrate more while coding... Commented Feb 2, 2017 at 0:24

1 Answer 1

6

The problem is that you're storing the values as strings, not numbers, and you're using the === operator, which doesn't perform type coercion between different types. count($pw_signs) - 1 will always be a number, not a string, all the === tests will fail.

Get rid of the quotes around all the numbers and it should work as desired. And if the source of the values is external, convert them to numbers with intval() before storing into the array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.