Jump to content

Array Manipulation


spelltwister

Recommended Posts

Hello everyone!

I was wondering, what i'm doing wrong with this code:

[code]<?php

$colors = array('red','green','blue');

unset($colors[1]);

for($i = 0;$i<sizeof($colors);$i++){

echo $colors[$i];

}

?>[/code]

Why does blue disappear too?

Also, what I was trying to do with that is remove just green and have the array size become 2 (0 and 1 have elements) so that i could randomly select from a larger list without hitting a blank. IE

[code]<?php

$colors = array('red','green','blue','orange','yellow','purple');

for($i=0;$i<6;$i++){
$rand = rand(0,sizeof($colors)-1);

echo $colors[$rand];

unset($colors[$rand]);
}

?>[/code]

Any ideas?

Here's what I really want to do:

[code]$defense_infantry = array( "nation" => array(), "number" => array() );

$upper = sizeof($offense_infantry["nation"]);
        $index = rand(0,$upper-1);
        if($offense_infantry["number"][$index] > 0){
           $attInfantry--;
           $offense_infantry["number"][$index] -= 1;
           $k+=1;
           echo 'Attacker lost an infantry to artillery</br>';
        }else{
          echo 'empty attacker infantry to artillery</br>'; <== I want to get rid of this posibility
        }
        if($offense_infantry["number"][$index] ==0){
          unset($offense_infantry["number"][$index]);
          unset($offense_infantry["nation"][$index]);
        }[/code]

Thanks

Mike
Link to comment
https://forums.phpfreaks.com/topic/4713-array-manipulation/
Share on other sites

[code]$colors = array('red','green','blue');

unset($colors[1]);

for($i = 0;$i<sizeof($colors);$i++){

        echo $colors[$i];

}[/code]

"blue" is still there but its key remains 2 so you don't echo it. Try

[code]$colors = array('red','green','blue');

unset($colors[1]);

foreach ($colors as $c) {

         echo $c;

}[/code]
Link to comment
https://forums.phpfreaks.com/topic/4713-array-manipulation/#findComment-16502
Share on other sites

you are amazing. any chace you would know how to apply it to the multi-dimensional array that i have? would be it like this:

$offense_infantry = array_values($offense_infantry);

so that each of the arrays in the array smash together?

or would it be like this:

$offense_infantry["nation"] = array_values($offense_infantry["nation"]);
$offense_infantry["number"] = array_values($offense_infantry["number"]);

Thanks so much. You rule
Link to comment
https://forums.phpfreaks.com/topic/4713-array-manipulation/#findComment-16540
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.