Changing value inside foreach loop doesn't change value in the array being iterated over

前端 未结 9 1908
轻奢々
轻奢々 2020-12-10 04:31

Why does this yield this:

foreach( $store as $key => $value){
$value = $value.\".txt.gz\";
}

unset($value);

print_r ($store);

Array
(
[1] => 101Phon         


        
相关标签:
9条回答
  • 2020-12-10 05:11
    foreach(array_container as & array_value)
    

    Is the way to modify array element value inside foreach loop.

    0 讨论(0)
  • 2020-12-10 05:12

    The $value variable in the array is temporary, it does not refer to the entry in the array.
    If you want to change the original array entry, use a reference:

    foreach ($store as $key => &$value) {
                           //  ^ reference
        $value .= '.txt.gz';
    }
    
    0 讨论(0)
  • 2020-12-10 05:13

    pass $value as a reference:

    foreach( $store as $key => &$value){
       $value = $value.".txt.gz";
    }
    
    0 讨论(0)
  • 2020-12-10 05:20

    Try

    foreach( $store as $key => $value){
        $store[$key] = $value.".txt.gz";
    }
    
    0 讨论(0)
  • 2020-12-10 05:20

    Try

    $catalog = array();
    
    foreach( $store as $key => $value){
        $catalog[] = $value.".txt.gz";
    }
    
    
    print_r ($catalog);
    

    OR

    foreach( $store as $key => $value){
        $store[$key] = $value.".txt.gz";
    }
    
    
    print_r ($store);
    

    Depends on what you want to achieve

    Thanks :)

    0 讨论(0)
  • 2020-12-10 05:22

    The doc http://php.net/manual/en/control-structures.foreach.php clearly states why you have a problem:

    "In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference."

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    // $arr is now array(2, 4, 6, 8)
    unset($value); // break the reference with the last element
    ?>
    

    Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:

    <?php
    /** this won't work **/
    foreach (array(1, 2, 3, 4) as &$value) {
        $value = $value * 2;
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题