Why doesn't this code work?

Don't understand why this isn't working.  When run, I get nothing in the browser.


<?php


function add ($x, $y) {
	$num = $x + $y;
	return $num;
}

add(3,4);

echo $num;


?>

Open in new window

LVL 1
LB1234Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
$num is only available within your function. You need something like this:


$answer = add(3,4);
echo $answer;

Open in new window

0
Chris StanyonWebDevCommented:
If you don't need to assign it, then:

echo add(3,4);

Open in new window

0
LB1234Author Commented:
I thought the whole point of "return" was to make sure something could be used OUTSIDE the function?
0
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

LB1234Author Commented:
If I return "$num" shouldn't $num be available outside the variable?
0
Chris StanyonWebDevCommented:
I thought the whole point of "return" was to make sure something could be used OUTSIDE the function?
It can - the value! You're not returning the actual variable, you're just returning the value of it;

function test () {
     return 1;
}

echo test(); //will echo 1

function add($x, $y) {
    return $x + $y;
}

echo add(4,3);

Open in new window

Often you won't have access to the function so you won't see what goes on inside of it. Whenever you call a PHP function, do you know what the variables are called inside that function. No! Assume I wrote your add() function, and told you to pass in 2 numbers and you'll get the answer - why would you care what I called the variables inside the function - you're only interested in the answer that comes out.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.