Simple PHP question involving functions?

<?php

$num1 = 5;

function int_ornot()

{

if(is_int($num1) == true)

{

echo "Num1 is an integer";

echo "<br />";

}

else

{

echo "Num1 is not an integer";

echo "<br />";

}

}

int_ornot();

?>

Some php code i written that works to some extent but theres an error and the outcome is the opposite (if num1 is an int it says its not an int and vice versa) can anyone spot the error and help me fix it ? Thanks

2 Answers

Relevance
  • 8 years ago
    Favorite Answer

    I ran your code and it did not work for me either. To make it work, i used

    <?php

    $num1 = 5;

    echo is_int($num1) ? "Num1 is Int": "Num1 is not Int";

    ?>

    must be something wrong with either your function call or the if statements.

    EDIT: These are ternary statements, follow the link to learn about them. good for replacing single line if-else blocks.

  • 8 years ago

    On the second line, you set "$num1 = 5:"

    As this declaration is OUT of any function, it becomes a GLOBAL variable that can be used anywhere in your code, at least AFTER it has been declared...

    However, for the variable to be used WITHIN a function, you must declare that variable as being a global!

    function int_ornot()

    {

    global $num1;

    ...

    You should also use the exact comparison (variable AND type) in your test, since is_int() returns a boolean, and "true" is also a boolean.

    Hence:

    if (is_int ($num1) === true) // "===" and not "=="

    and, for this stupid editor, here, don't use the proper < b r / >, just use the false one: <br>! Makes things easier to read! :-)

    Source(s): http://webprosonly.com/ - Professional developers for professional buyers
Still have questions? Get your answers by asking now.