Andrew Andrew - 1 month ago 14
PHP Question

Confusing Function Output

I am really confused with the outcome of the following function. I know that its a small snippet of code but I think there is enough information to understand what is supposed to happen:

while ($k < $dateCount) {
echo $k." ==> ".$forecastData[$k]['Booked Date']." ==> ".$startDate."<br>";
if($forecastData[$k]['Booked Date'] == $startDate){
echo $k." ==> YAY<br>";
}
else{
echo $k." ==> boo ==> ".$startDate."<br>";
}
$k++;
$startDate = date('Y-m-d', strtotime("+1 day", strtotime($startDate)));
}


$k is the array key -> starts at 0;

$dateCount is the size of the array (to stop it at the 31 days or however long the range is)

$forecastData is a multidimensional array of all sales data for a date. – contains loads of information for that date including the booked date which is the day the information is stored for.

$startDate is the date that has been put in but converted to the same day last year – in this case the date put in is Oct 01 2016 and the converted date is Sep 26 2015

I want to say that if the dates are equal then echo the number of the array with the word YAY otherwise echo the array number with the word boo.

The k increases by 1 per loop as does the date.

I have also printed the initial values of the loop to show me what the comparison is.

What I cant understand is that this is the output:


0 ==> 2015-09-26 ==> 2015-09-26

0 ==> boo ==> 2015-09-26

1 ==> 2015-09-27 ==> 2015-09-27

1 ==> YAY

2 ==> 2015-09-28 ==> 2015-09-28

2 ==> YAY

3 ==> 2015-09-29 ==> 2015-09-29

3 ==> YAY

4 ==> 2015-09-30 ==> 2015-09-30

4 ==> YAY

5 ==> 2015-10-01 ==> 2015-10-01

5 ==> YAY

6 ==> 2015-10-02 ==> 2015-10-02

6 ==> YAY

7 ==> 2015-10-03 ==> 2015-10-03

7 ==> YAY

8 ==> 2015-10-04 ==> 2015-10-04

8 ==> YAY

9 ==> 2015-10-05 ==> 2015-10-05

9 ==> YAY

10 ==> 2015-10-06 ==> 2015-10-06

10 ==> YAY

11 ==> 2015-10-07 ==> 2015-10-07

11 ==> YAY


The first one makes NO sense to me?? It does equal what it should but for some reason skips by it?? Also if I hardcode the date in then it will work.

I have been trying to understand this for so long now that any ideas will help

Thank you

Answer

From your output I see that highlighting 2015-09-26 also will select trailing white space while highlighting 2015-09-27 has no trailing space.

So it means 2015-09-26 != 2015-09-26_. Use trim($startDate) or just check from where this trailing white space is coming.

Also when debugging it's better to use var_dump($startDate); => string(11) "2015-09-26 ". That way you will also see string length.


From personal experience
Was comparing hello to hello it it failed. Turns out var_dump($var); shows hello length as 10. Further investigation showed that it's \0h\0e\0l\0l\0o