Search code examples
phpglobal-variablespass-by-reference

PHP Basics: Global variables & references



I'm not sure what I'm missing here; I'm trying to understand fundamentals.

The goal is to build a function that starts with the string Smith, turns it lowercase into smith then reverses it into htims. Then use the built-in str_repeat() function to print it 10x in a vertical column like such:

htims
htims
htims
htims
...
x10

This is what I got:

01 function reverseString(&$lname)
02 {
03   $lname = "Smith"; // Starting off with Smith
04   $lname = strtolower($lname); // Lowercases Smith into smith
05   return strrev($lname); // Reverses smith into htims
06 }
07 
08 echo reverseString($lname); // Testing my function = success. Prints htims.
09 echo "\n \n"; // Added line break. Now to try to use a built-in function to print it 10x..
10 echo str_repeat(reverseString($lname), 10); // Prints htimshtimshtimshtimsh .. x10

So far so good.

Now I want to add a line break between the repeated strings so instead of printing htimshtimshtimshtimsh .. x10 it prints:

htims
htims
htims
...
x10

This is where I got stuck.

Attempt #1

I can't concatenate in the functions parameters:

echo str_repeat(reverseString($lname . "\n"), 10); // Does not print. Fine, I'm assuming it's not appropriate syntax.

Attempt #2

I can't reassign $lname a value outside of the function before the last echo:

10 $lname = $lname . "\n";
11 echo str_repeat(reverseString($lname), 10); // Does not print. Assuming because the variable does not have global scope.

Attempt #3

So I tried making $lname a global variable in the function before anything else:

01 function reverseString(&$lname)
02 {
03   global $lname; // Tried giving $lname global scope
04   $lname = "Smith";
05   $lname = strtolower($lname);
06   return strrev($lname);
07 }

...

10 $lname = $lname . "\n"; // But reassignment outside of the function STILL does not work.
11 echo str_repeat(reverseString($lname), 10); // Does not print.

Last ditch effort attempt #4

I tried giving global scope outside of the function for good measure. Did not work either:

01 function reverseString(&$lname)
02 {
04   $lname = "Smith";
05   $lname = strtolower($lname);
06   return strrev($lname);
07 }
08
09   global $lname; // Tried giving $lname global scope

Workaround

Adding the line breaks in the function works but I have to place them before my strings since eventually it will be reversed:

01 function reverseString(&$lname)
02 {
03   $lname = "\nSmith"; // Option 1
04   $lname = strtolower("\n" . $lname); // Option 2
05   return strrev("\n" . $lname); // Option 3
06 }

What I want to know is why trying to make $lname a global variable and reassigning it a new value did not work any way I tried.


Solution

  • What you can do is add the new line after getting the value back from the function....

    echo str_repeat(reverseString($lname) . "\n", 10);