Problem with functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
srirams
Forum Commoner
Posts: 36
Joined: Wed May 25, 2005 8:57 am
Location: India
Contact:

Problem with functions

Post 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.
GM
Forum Contributor
Posts: 365
Joined: Wed Apr 26, 2006 4:19 am
Location: Italy

Post 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.
srirams
Forum Commoner
Posts: 36
Joined: Wed May 25, 2005 8:57 am
Location: India
Contact:

Post 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
jamiel
Forum Contributor
Posts: 276
Joined: Wed Feb 22, 2006 5:17 am
Location: London, United Kingdom

Post by jamiel »

As with anything ... Practice and Learn from the experienced.
Post Reply