0

Some functions I have used return a string on echo, something like this.

echo my_function();

This prints "hello" on the screen.

print_r( my_function() );

This prints an array or an object on the screen. The function is the same in both cases, even the possible in parameters.

How is this done?

The possible function

function my_function() {
    // If this function is used by echo return the string
    // If this function is used by print_r return an array

    $string = 'Hello';
    $array = array('some', 'data');

    // return $string or $array depending on
}

Real life example

This function return an image on echo and an object on print_r: http://getkirby.com/docs/cheatsheet/helpers/thumb

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

2 Answers2

0

Your my_function() is not returning anything. So calling it in echo or print_r makes no diffrence. If you return string form the function and you want to just display it then you can echo it out. But if you return array from function and echo it then it will give you a unusful output. On the other hand if you print_r the function and function return string, then it will output just like echo do. But if you return array and call with print_r then it will show the array more readable. It is useful for debugging.

Here is more about echo and print_r()

echo

  1. Outputs one or more strings separated by commas
  2. No return value

print_r()

  1. Outputs a human-readable representation of any one value
  2. Accepts not just strings but other types including arrays and objects, formatting them to be readable
  3. Useful when debugging
  4. May return its output as a return value (instead of echoing) if the second optional argument is given
Imran
  • 4,582
  • 2
  • 18
  • 37
-1

Functions should never depend on who they called, but how they are called.

There is no sense in for example creating a function that does addition on echo and subtraction on print. That is confusing.

try to use parameters as suggested in the question's comments.

devnull
  • 558
  • 4
  • 18