0

I'm trying to code a site similar to the coding on the bottom. I need help though I'm not sure if functions for php can work this way. I want to be able to use the function greeting in many different if else statements. How can i do this without having to plug the entire code in to every if else statement. Thanks

function greeting(){
if($greetings == hello){
  echo "Hello";
}else{
  echo "goodbye";
}
}
if($occupancy > 0){
  function greeting()
}else{
  echo "Nobody is home";
}
5
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by twiss
0

Your question isn't quite clear.
Why don't you put all reasonling into function greetings

function Greetings()
{
    if($occupancy < 1) return "Nobody is home";

    if($greetings == hello)
    {
        return "Hello";
    }
    else
    {
        return "goodbye";
    }
}

Calling Greetings

echo Greetings();
//or
print Greetings();
0

Hi
i think this is the right way to call a function in if else statements

if($occupancy > 0){
greeting()
}else{
echo "Nobody is home";
}

0

You can use like this

<?php
    
	function greeting()
	{
		if($greetings == hello)
		{
			echo "Hello";
		}
		else
		{
			echo "goodbye";
		}
    }
if($occupancy > 0)
    {
    	greeting();
    }
    else
    {
    	echo "Nobody is home";
    }
?>

just remove the function keyword in function call and place ';' at the end of function call.

0

This won't work. In PHP, you can access variables outside a function only if you make them global or pass them in as arguments (the latter is probably what you want).

function greeting($occupancy, $greeting)
{
    if($occupancy < 1) return "Nobody is home";
 
    if($greeting == 'hello') return "Hello";
    else return "Goodbye";
}


// Than, you can call it like this:

$occupancy = 1;
$greeting = 'hello';
echo greeting($occupancy, $greeting); // "Hello"

$greeting = 'somethingelse';
echo greeting($occupancy, $greeting); // "Goodbye"

$occupancy = 0;
echo greeting($occupancy, $greeting); // "Nobody is home"

Edited by twiss: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.