开发者

Understanding an interesting array update/replace function

I'm a PHP amateur.

This array function is an adaption of a function I noticed while reading this article.

I thought this was an interesting type of array function, but I have a question about the way it works.

my_func( array( 'sky' => 'blue' ) );

function my_func( array $settings = array() ) 
{  
   $settings = $settings + array( 'grass'=>'green','sky'=>'dark' );
   print_r( $settings ) ;  
   // outputs: Array ( [sky] =开发者_Go百科> blue [grass] => green )  
}

but.....................

my_func( array( 'sky' => 'blue' ) );

function my_func( array $settings = array() ) 
{ 
   $settings = array( 'clock'=>'time' ) ;
   $settings = $settings + array( 'grass'=>'green','sky'=>'dark' );
   print_r( $settings ) ;  
   // outputs: Array ( [clock] => time [grass] => green [sky] => dark ) 
}

Why does [sky] not equal 'blue' in the second instance?

Thanks.


$settings is overwritten by clock=time on the first line. sky=blue never makes it into the array.

You're passing sky=blue into the function as $settings, but then $settings is defined again on the first line of the function.


    my_func( array( 'sky' => 'blue' ) );

    function my_func( array $settings = array() ) 
    { 
print_r($settings);// It will print Array ( [sky] => blue ) .After that it is over written
       $settings = array( 'clock'=>'time' ) ;
       $settings = $settings + array( 'grass'=>'green','sky'=>'dark' );
       print_r( $settings ) ;  
       // outputs: Array ( [clock] => time [grass] => green [sky] => dark ) 
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜