2014-09-26 57 views
2

未定义变量为$new_string

我写了这个小脚本,因为我需要它,(不要问为什么)。

$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; 

我知道我可以简单地说,$new_string = NULL在一开始就避免了未定义的变量,但它不能帮助我理解为什么它没有被定义。

非常外行的说法,$r等于数组中每对的值?

$new_string如何等于$r

回答

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

$new_string .= $r;意味着$new_string = $new_string . $r;这里要附加$r到未声明或该代码,即,不存在前定义的变量$new_string的值。您可以通过声明以上foreach像变量解决这个问题:

$new_string=""; 
foreach($reverse as $r) { 
     $new_string .= $r; 
     } 
+0

implode功能我明白了。谢谢。我认为第一个循环将被认为是等于,并且后面的循环是附加的。我的假设是错误的。 – Tom 2014-09-26 05:27:42

+0

@汤姆。总是欢迎。很高兴帮助你:) – Jenz 2014-09-26 05:28:38

0

没有错误在你的程序的输出: -

http://codepad.org/9FDqrh3D

它给gthe正确的输出为$ new_string

+0

http://3v4l.org/3c17q – sectus 2014-09-26 05:25:13

+0

@abhinsit对不起,我忘记提及代码按计划运行。我一直在使用它。我打开error_log并看到充满未预期的未定义变量通知的页面。 – Tom 2014-09-26 05:34:46

+0

当然,在抑制error_reporting时,通知不会显示,但问题仍然存在。 – Christian 2014-09-26 05:35:10

1

OP正在寻找解决方案,其中$ new_string不需要事先初始化。

的解决方案是使用PHP

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

不错。谢谢。虽然我不知道名字,但Implode是我偶然发现的功能,当我偶然发现可以使用。= $ r来组合输出对时。 – Tom 2014-09-28 03:41:26