Jump to content

Replace value in associative array using foreach()


shreyaskudav
 Share

Recommended Posts

This is how I defined the array:

$j = 1;while($j < $i){$battlepokemon[$j] = array('battle_poke' => $battle_poke[$j], 'battle_level' => $battle_level[$j], 'battle_health' => $battle_health[$j]);$j++;}

So the structure is something like this:

battlepokemon[1]{battle_poke => xxxxbattle_level => 10battle_health => 50}battlepokemon[2]{battle_poke => xxxxbattle_level => 10battle_health => 50}... and so on... 

Lets say.. I want to replace the value battlepokemon[1] => battle_health(key) from 50 to 100 using foreach()..

How should I do that??

 

I don't want to do it manually like: $val[$key] = 100; or something like that...!

 

 

 

Link to comment
Share on other sites

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

As you said dsonesuk!

This code is working properly..only the assignment of '0' to the attr $value['battle_health'] is not working! is the statement correct??

Link to comment
Share on other sites

?? I don't $opponent_increment relates to, but I'm guessing the $j increment or now the index value used for in original post battlepokemon[1] or battlepokemon[2]

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

but you could get same result with

        foreach ($battlepokemon as $key => $value) {            if ($key== $opponent_increment) {                $battlepokemon[$key]['battle_health'] = 0;                echo "Data replaced!";            }        }
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...