0

The below is my array, where I need to replace the value of 'battle_health'

$battlepokemon= array();

$i = 1;
while($rows = mysql_fetch_assoc($res))
{
$path = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$rows['pkmn_id']."' ");
$pokemon = array(
'opponent_increment' => $i,
'id' => $rows['pkmn_id'],
'battle_poke'=> mysql_result($path,0,"path"),
'battle_level' => $rows['level'],
'battle_health' => $rows['health']
);
$i++;
$battlepokemon[]= $pokemon;
}

The code for replacement is:

$i = 1;
foreach ($battlepokemon as $key => $value) 
{
if($value['opponent_increment'] == $opponent_increment)
{
$value['battle_health'] = 0;
echo "Data replaced!";
}
$i++;
}
print_r($battlepokemon);

The code above is working..from start to end.. but the value is not replaced with '0' as the code says! I think I must have missed something!

3
  • your replacing in the temporary copy of the array php creates for the loop, not the original Commented Aug 22, 2014 at 3:59
  • Where is $opponent_increment defined ? what is the value ? Commented Aug 22, 2014 at 3:59
  • 3
    change foreach ($battlepokemon as $key => $value) to foreach ($battlepokemon as $key => &$value) Commented Aug 22, 2014 at 4:07

2 Answers 2

4

You need to transfer the reference, not the values. Add a & to the following sentence

foreach ($battlepokemon as $key => &$value) 
                                   ^

I tried this just for example

<?php
$arr = array('12', '34');
foreach($arr as $key => &$value){
  $value = 0;
}
var_dump($arr);
?>

Hopes it can help you

Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve this with for Loop Because unlike foreach loop, it doesn't perform an array copy before transversal:

$arr = array('12', '34');
for($i = 0, $count = count($arr); $i < $count; $i++){
    $arr[$i] = 0;
}
var_dump($arr);

Or If you want to do with Foreach only, you need to avoid new copy of array by passing the reference like:

   $arr = array('12', '34');
   foreach($arr as $key => &$value)
   {
       $value = 0;
   }
   var_dump($arr);

1 Comment

Downvoted as the code you supplied is quite inefficient. You can use a foreach loop, you just need force the value to be a reference (noted in another answer) or refer to the scoped array variable. You must also be careful with a count in your for loop. The second argument of your for loop will be executed every iteration. The more efficient code is: for($i = 0, $count = count($arr); $i < $count; $i++)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.