Search code examples
phpstring-comparison

two strings identical, but not equal when compared


I have this little problem i couldn't solve on my own, i'm comparing two strings that are identical one taken from the database and the other from a text file, the values are always equal except for the last one

CODE FOR ARRAY FROM TEXT FILE

while (!feof($monfichier)) {
    $line = fgets($monfichier);
    $pieces = explode(" ", $line);
    $factureAgent[$nbb][0] = $pieces[0]; //id client
    $factureAgent[$nbb][1] = $pieces[1]; //consommation annuelle
    $factureAgent[$nbb][2] = $pieces[2]; //année
    $factureAgent[$nbb][3] = $pieces[3]; //id agent
    $month = explode(":", $pieces[4]);
    $factureAgent[$nbb][4] = $month[1]; //janvier
    $month = explode(":", $pieces[5]);
    $factureAgent[$nbb][5] = $month[1]; //fevrier
    $month = explode(":", $pieces[6]);
    $factureAgent[$nbb][6] = $month[1]; //mars
    $month = explode(":", $pieces[7]);
    $factureAgent[$nbb][7] = $month[1]; //avril
    $month = explode(":", $pieces[8]);
    $factureAgent[$nbb][8] = $month[1]; //mai
    $month = explode(":", $pieces[9]);
    $factureAgent[$nbb][9] = $month[1]; //juin
    $month = explode(":", $pieces[10]);
    $factureAgent[$nbb][10] = $month[1]; //juillet
    $month = explode(":", $pieces[11]);
    $factureAgent[$nbb][11] = $month[1]; //aout
    $month = explode(":", $pieces[12]);
    $factureAgent[$nbb][12] = $month[1]; //septembre
    $month = explode(":", $pieces[13]);
    $factureAgent[$nbb][13] = $month[1]; //octobre
    $month = explode(":", $pieces[14]);
    $factureAgent[$nbb][14] = $month[1]; //novembre
    $month = explode(":", $pieces[15]);
    $factureAgent[$nbb][15] = $month[1]; //decembre
    $nbb++;
}

HERE IS THE CODE

echo "<br>".$row[0]."is".$factureAgent[$i][$nb]."<br>";
if ($année==$annéeComp[0]) {
  if ($row[0]!=$factureAgent[$i][$nb]) {
    echo "<br>".$row[0]."is".$factureAgent[$i][$nb]."<br>";
    $ok = false;
  }
  $nb++;
  $nbr++;
}

OUTPUT

25is25
50is50
87is87
115is115
200is200
250is250
400is400
550is500
600is600
650is650
800is800
950is950
950is950

see image

LINE I'M READING FROM TEXT FILE

1 2000 2019 1 01:25 02:50 03:87 04:115 05:200 06:250 07:400 08:550 09:600 10:650 11:800 12:950
13 2000 2019 1 01:45 02:90 03:150 04:300 05:600 06:800 07:1000 08:1300 09:1450 10:1600 11:1800 12:2000

see image


Solution

  • Comparing string from different sources can lead to unexpected results.

    One thing you can do is casting your values to the same type and then compare. For example:

    if (intval('1') === intval('01')) ...

    This way you are getting the two sides to integer and its just an integer comparison.

    Note that if you cast a value which is not numeric the function will always return 0