Page 1 of 1

Problem with functions

Posted: Tue Jul 11, 2006 3:36 am
by srirams
Hi I am unable to get a solution for the below program.
<?php



function is_even($param1)
{
if (($param1 % 2) == 0)
return TRUE;
else
return FALSE;
}

$num = 5;
echo 'The number is a' . is_even($num);


?>


This is actually not returning anything.
How do I call this function for me get the string" The number is odd"

Please help.

Posted: Tue Jul 11, 2006 3:45 am
by GM
This should do it.

You are returning either true or false, so we can test this value and set our variable based on it. Another option would be to return strings from the function (instead of returning boolean TRUE, return string "even" etc.), but this would make the function less flexible.

Code: Select all

function is_even($param1) 
{ 
if (($param1 % 2) == 0) {
    return TRUE; 
} else {
    return FALSE; 
} 

$num = 5;
$outString = "";
if(is_even($num)) {
    $outString = "even";
} else {
    $outString = "odd";
} 

echo "The number is $outString";
Another way might be to use the ternery "if":

Code: Select all

function is_even($param1) 
{ 
if (($param1 % 2) == 0) {
    return TRUE; 
} else {
    return FALSE; 
} 

$num = 5;
echo "The number is ".(is_even($num) ? "even" : "odd");
EDIT: Tidied up the syntax in the is_even function if statement.

Posted: Tue Jul 11, 2006 7:50 am
by srirams
Excellent.

Tried both and both of them worked.

Thank you very much for the help.

Whats the best way to learn PHP well? I would want to master this.

Thanks

Posted: Tue Jul 11, 2006 7:56 am
by jamiel
As with anything ... Practice and Learn from the experienced.