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";
}

Recommended Answers

All 4 Replies

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();

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";
}

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.

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"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.