1. The forums will be archived and moved to a read only mode in about 2 weeks (mid march).

problem setting array from foreach

Discussion in 'Development' started by Atomization, Nov 16, 2018.

  1. Atomization

    Atomization Baby Zombie

    Messages:
    120
    GitHub:
    iAtomPlaza
    hey, i have an array in my config which looks like: it is the data of a minigame plugin im working on...
    Code:
    ---
    world1:
      blueSpawn:
      - 10.672100
      - 55.000000
      - 54.887200
      redSpawn:
      - 10.426900
      - 55.000000
      - 9.509000
    world2:
      blueSpawn:
      - 10.480700
      - 55.000000
      - 54.954100
      redSpawn:
      - 10.459800
      - 55.000000
      - 9.431400
    ...
    
    however, i have a foreach loop in the `onEnable()` function that will `unset` the spawnpoints so im left with just the names of the worlds and `$this->arenas` is set with the array in the config via the `if statment`
    PHP:
    public $arenas = [ ]; /* when plugin command is run, the world gets pushed into the array */
    public function onEnable () {
        if(
    $this->config->getAll() != null) {
            
    $this->arenas $this->config->getAll();
        }
    /* so in this onEnable function it gets the whole config */

        
    foreach($this->arenas as $level => $value){
            
    $key array_search($value$this->arenas);
            unset(
    $this->arenas[$key]); /* then its suposed to unset everything and leave the names of the worlds */
            
    $this->arenas = []; //back to default value of the array
            
    array_push($this->arenas$level); //pushes the names back into the array as if the command was run, thus, creating the minigame levels
        
    }
        
    var_dump($this->arenas);
    }
    And my problem is that only the last item in the array (world2) is set in the array when i `var_dump($this->arenas)` at the end.
     
  2. Atomization

    Atomization Baby Zombie

    Messages:
    120
    GitHub:
    iAtomPlaza
    the var_dump
    Code:
    array(1) {
      [0]=>
      string(6) "world2"
    }
    
     
  3. Muqsit

    Muqsit Chicken

    Messages:
    1,548
    GitHub:
    muqsit
    Remove the...
    PHP:
    $this->arenas = [];
    line. You're emptying the array right before pushing an entry into it, which is why you're ending up with an array of 1 entry.

    Side note: $key = $level in your case, no need to array_search() that.
    You can directly use array_keys() instead of the foreach loop, it seems like you're coding your own array_keys. :oops:
     
    jasonwynn10 likes this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.