Is it possible to find 'this' in a foreach?

2

I have the following script:

$arr = [
   10 => [
      'Xa' => 'xA'
   ],
   32 => [
      'Xb' => 'xB'
   ],
   45 => [
      'Xc' => 'xC'
   ],
   78 => [
      'Xd' => 'xD'
   ]
]
foreach($arr as $var){

   if($var['Xa'] == 'xA'){
      //Nesta escapatória encontrar 'this' para modificar $arr[10] 
   }
}
  • Can you find 'this' within if without using 'key' ?

The context of the question is that in a given loop (of a growing non-sequential array) I need to append data to this array, and I can not access its key because some unsets are given at the time of construction.

Previously it worked with this (before adding the unsets), but it is not working anymore and is adding keys that no longer exist in the array:

$c = 0;
foreach ($return as $rs_row) {
    foreach ($rs_flag as $flag) {
        if ($rs_row['id'] == $flag['relationship']) {
            $return[$c]['flag'] = $flag['flag'];
            $return[$c]['flag-cod'] = $flag['cod'];
            $return[$c]['flag-observations'] = $flag['observations'];
        }
    }
    $c += 1;
}
    
asked by anonymous 08.11.2017 / 16:53

1 answer

2

The solution was found right after the question, just add the key pickup:

foreach ($return as $rs_key => $rs_row) {
    foreach ($rs_flag as $flag) {
        if($rs_row['id'] == $flag['relationship']) {
            $return[$rs_key]['flag'] = $flag['flag'];
            $return[$rs_key]['flag-cod'] = $flag['cod'];
            $return[$rs_key]['flag-observations'] = $flag['observations'];
        }
    }
}

Another, however, out of ignorance I was missing the syntax:

  • Correct

    foreach($arr as $key => $target) {
        //
    }
    
  • Wrong (like I was doing)

    foreach($arr as $key -> $target) {
        //
    }
    

With this I would receive an error and conclude that I could not access the array erroneously.

    
08.11.2017 / 17:22