user3428247
user3428247

Reputation: 21

PHP Defining Function Logical

I am just starting out learning php, and I was wondering someone can help me out with the logical of defining functions. I can't seem to wrap my head around it.

Simple Example:

<?php

function hello($word) {
  echo "Hello $word";
}

  $name = "John";
  strtolower(hello($name))

?>

I know if I use return instead of echo in the function and then echo it outside defining the function, the "strtolower" applies, but in this example it doesn't. I don't get how php is interpreting it. Thanks in advance.

Upvotes: 1

Views: 52

Answers (1)

kero
kero

Reputation: 10638

Imagine a function is a box of unknown content. You put something in and something comes out - meaning you have parameters and something to be returned.

In your code example you don't return anything, instead echo some string.

function hello($word) {
//             ^ parameter
  return "Hello $word";
}

$name = "John";
strtolower(hello($name));

To explain a bit further, you can look at your original code this way:

echo strtolower(hello("John"));
     ^          ^--- call hello("John")
     |                something happens (your echo)
     |               hello() ended without return, return NULL by default
     |--- call strtolower( NULL )
            something happens
          strtolower() returned ""

But you want it to be like this:

echo strtolower(hello("John"));
     ^          ^--- call hello("John")
     |                something happens
     |               hello() return "Hello John"
     |--- call strtolower("Hello John")
            something happens
          strtolower() returned "hello john"

Upvotes: 6

Related Questions