Ciprian
Ciprian

Reputation: 3226

Simple if else statement won't work

I have a page.html with just 48 in it. I can't get this if statement to work.

<?php 
  $myFile = 'http://site.com/page.html';
  $content = file_get_contents($myFile);
?>
<?php $num = "48"; ?>
<?php if ($content == $num): ?>
    true
<?php else: ?>
    false
<?php endif;  ?>

If I do this it works.

<?php if ($content == 48): ?>
    true
<?php else: ?>
    false
<?php endif;  ?>

How can I change this to make it work?

Upvotes: 2

Views: 455

Answers (3)

Wouter Dorgelo
Wouter Dorgelo

Reputation: 11978

Think this should work:

<?php 
  $myFile = 'http://site.com/page.html';
  $content = file_get_contents($myFile);
?>
<?php $num = "48"; ?>
<?php if (trim($content) == $num): ?>
    true
<?php else: ?>
    false
<?php endif;  ?>

..by using trim() which removes these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Upvotes: 1

Todd Baur
Todd Baur

Reputation: 1005

You're evaluating a string in the first snippet an integer in the second. Make sure you casting it to an integer if that's they data type you're after.

$content = (int) file_get_contents($myFile);

Upvotes: 0

cmbuckley
cmbuckley

Reputation: 42458

Most likely the value of $content contains "48\n", i.e. the number 48 followed by a new line (or something similar). This is equal (with non-strict comparison) to the int 48, but not to the string "48".

The way to work around it is to cast $content to an int before making the comparison:

$content = (int) file_get_contents($myFile);

Upvotes: 2

Related Questions