Why echo error?

I passed the exercise with below code…

function convertToShout($string)
{
$Nstring = $string . "!";
  return strtoupper("$Nstring");
}
convertToShout("all upper");

but the same code throws error when i try to add echo at the end as…

echo convertToShout();

Why?

Hey there @netrunner36592!

If I understand your situation correctly, your code should look like this:

function convertToShout($string)
{
$Nstring = $string . "!";
  return strtoupper("$Nstring");
}
convertToShout("all upper");

echo convertToShout();

In this case, you are receiving an error because you are trying to call a function that requires the arguement, $string, without providing it.

If you give the function an arguement, such as:

echo convertToShout("over here"); //will echo: OVER HERE

Than your function has the information it needs and will work properly.


A useful thing to know is that you can set a default value for a function arguement by assigning it when you write the function.
In the event the function is called and an arguement is ommited, this value will fill in for it:

function add($numberOne=5, $numberTwo=5) {
  return $numberOne + $numberTwo;
}

echo add(3, 3); //echos 6
echo "\n";
echo add(3);    //echos 8
echo "\n";
echo add();     //echos 10

1 Like

@8-bit-gaming does that mean that echo must have an argument if the respective function has argument?

Because in php course i have used echo function_name(); many times without any error.

The function has an argument… all you are doing when you echo a particular function is echoing the value that it returns. In order for this function to run, it needs an argument (that’s how you’ve defined it). How you call a function doesn’t change simply because its output is passed to an echo statement.

So, if a function is defined as my_func(){}, you can echo it without any arguments… because it doesn’t take any arguments. my_func($foo){}, however, takes an argument, so to echo it, you need to pass it an argument.

TL;DR: Functions are functions, no matter where they are being called.

1 Like