2

The undefined variable is $new_string.

I wrote this little script because I needed it, (don't ask why).

    $string  = "abcdefghijklmnopqrstuvwxyz"; // just used as an example

    // $string becomes "badcfehgjilknmporqtsvuxwzy"

    $now_in_pairs = str_split($string, 2);

    $reverse = array_map('strrev', $now_in_pairs);

    foreach($reverse as $r)   { 

    $new_string .= $r;  

    }

    echo $new_string;

I know I could simply say, $new_string = NULL at the start to avoid the Undefined variable but that doesn't help me to understand why it isn't defined.

In very layman's terms, $r equals the value of each pairs in the array?

How can $new_string be undefined when it equals $r?

3 Answers 3

2
foreach($reverse as $r)   { 
    $new_string .= $r;  
    }

$new_string .= $r; means $new_string = $new_string . $r; Here you are appending $r to the value of variable $new_string which is not declared or defined before this code ie, which doesn't exist. You can solve this issue by declaring the variable above foreach like :

$new_string="";
foreach($reverse as $r)   { 
        $new_string .= $r;  
        }
Sign up to request clarification or add additional context in comments.

1 Comment

I understand. Thank you. I assumed the first loop would be considered the equals and the following loops be the appended. My assumption was wrong.
1

The OP is looking for solution where $new_string doesnt need to be initialized beforehand.

The solution is to use the implode function of PHP

$new_string = implode($reverse);
//another usage with glue parameter:
//$new_string = implode('', $reverse);

1 Comment

Nice. Thank you. Although I didn't know the name, Implode was the function I was actually looking for when I stumbled upon that I could use .= $r to combine the output of the pairs.
0

There is no error in the output of your program:-

http://codepad.org/9FDqrh3D

Its giving gthe correct output for $new_string

2 Comments

@abhinsit Sorry I forgot to mention that the code works as planned. I've been using it. I opened the error_log and saw the page full of undefined variable notices that I didn't expect to find.
Sure, when suppressing error_reporting, the notice won't be shown, but the problem still exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.