for-looparray-push

PHP For Loop Array Push


I have a function that I call from a for loop. I'd like to collect and return all token ids once the loop is finished. However it only returns the last token id. It doesn't collect them in an array. Not sure what im doing wrong here?

for ($i = 0; $i < 20; $i++) {
     $return_info = make_pet($connect);
}

function make_pet($connect) {
    $token_id = rand(100,1000);
    $tokens[] = $token_id;
    return("tokens"=>$tokens);
}

Solution

  • You're recreating the array every time you run the function and so you'll only get the last token id. I haven't tested this, but it should be updated to something like:

    $tokens[];
    for ($i = 0; $i < 20; $i++) {
        $tokens[] = make_pet($connect);
    }
    
    function make_pet($connect) {
        $token_id = rand(100,1000);
        return("tokens"=>$tokens);
    }
    

    So your tokens array doesn't get overwritten every loop iteration. I'm not sure if that's the final shape you want your tokens array to take, but you should be able to modify accordingly.