Search code examples
phparraysarray-push

array_push multiple values based on variable?


I am trying to create an array with values repeated according to some variables. In this scenario: $slipszero = "2" & $slipsone = "1", and those values can change.
This is my code as of now:

$problist = array();
    foreach ($rows as $value) {
        if ($value['f_count'] == 0) {
            $placeholder = rtrim(str_repeat($value["uid"] . ',', $slipszero), ', ') ;
            array_push($problist, $placeholder);
            // The above array_push should act just like:
            array_push($problist, $value['uid'], $value['uid']);
        } elseif ($value['f_count'] == 1) {
            $placeholder = rtrim(str_repeat($value["uid"] . ',', $slipsone), ', ') ;
            array_push($problist, $placeholder);
        } elseif ($value['f_count'] >= 2) {
            $problist[] = $value['uid'];
        }
    }

So, starting with this array:

Array ( 
 [0] => Array ( [uid] => 105 [f_count] => 0 ) 
 [1] => Array ( [uid] => 106 [f_count] => 1 ) 
 [2] => Array ( [uid] => 107 [f_count] => 0 ) 
 [3] => Array ( [uid] => 108 [f_count] => 1 ) 
 [4] => Array ( [uid] => 109 [f_count] => 2 ) 
)  

I'd like to end up with this array:

array(15) { 
[0] => string(3) "105" 
[1] => string(3) "105" 
[2] => string(3) "106" 
[3] => string(3) "107" 
[4] => string(3) "107" 
[5] => string(3) "108" 
[6] => string(3) "109"
}  

Instead, I'm getting this:

Array ( 
[0] => 105,105 
[1] => 106 
[2] => 107,107 
[3] => 108
[4] => 109
)

Taking care of a newborn has shot my brain, because I cannot figure out what I'm doing wrong.


Solution

  • $newArray = array();
    foreach ($array as $subarray) {
        $i = 1; // default value
        if ($subarray["f_count"] === 0)
            $i = $slipszero;
        if ($subarray["f_count"] === 1)
            $i = $slipsone;
        while ($i--)
            $newArray[] = (string)$subarray["uid"];
    }
    

    This is adding $i times the string to the array where $i is depending on $subarray["f_count"].