-1

I have this piece of code :

$start = ['23','', 'what'];
foreach($start as $i){
  if($i ==''){
    $i = 'satisfaction';
  }
}
print_r($start);

The output is :

Array
(
[0] => 23
[1] => 
[2] => what
)

Why did index [1] not get replaced with 'satisfaction'. In other words : I don't want to create a new array, but change the index of an existing array. Actually, what I'm trying to achieve is to do intval() on those indexes that are not empty (since intval on an empty index returns 0, which is not what I want).

Dan
  • 10,614
  • 5
  • 24
  • 35
thiebo
  • 1,339
  • 1
  • 17
  • 37

3 Answers3

3

According to the manual:

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.

So in your case, you should add &:

$start = ['23','', 'what'];
foreach($start as &$i){
               // ^ reference
    if($i === ''){
        $i = 'satisfaction';
    }
}

Sidenote: If your intent is to change those numeric values into data type integer, you can use (as you stated) intval or a simple type cast.

$start = ['23','', 'what'];
foreach($start as &$i){
    if(is_numeric($i)){
        $i = (int) $i;
    }
}

var_dump($start);
Kevin
  • 41,694
  • 12
  • 53
  • 70
2

Because foreach(...) acts "a bit" as a read-only iterator. If you want to modify elements, you'll have to access by reference.

example :

foreach ($start as &$i) {

}

For more info, see doc : http://php.net/manual/fr/control-structures.foreach.php

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Cr3aHal0
  • 809
  • 4
  • 11
1

In your example you are just setting the variable $i, which is just a temporary variable for the loop. Instead, keep the array key in the loop and use that to set the value in the array:

$start = ['23','', 'what'];
foreach($start as $k=>$i){
  if($i ==''){
     $start[$k] = 'satisfaction';
  }
}
Dan
  • 10,614
  • 5
  • 24
  • 35