Setting a variable from an Array values in Laraval

The dump of the following array is :

$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
array(2) { [60]=> int(116) [50]=> int(117) } 

As shown above, the key is 60 and 50 (which is qcounter), while the value is 116 and 117 (which is id).

I'm trying to assign the qcounter to a variable as follows, but with a fixed index, such as 0,1,2,3 .. etc :

$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];

And the same with id :

$id1= $quest_all[0];
$id2= $quest_all[1];

Any help is appreciated.

3 answers

  • answered 2019-10-15 17:06 Julyano Felipe

    To reset array keys, use array_values(). To get array keys, use array_keys():

    $quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
    $quest_all_keys = array_keys($quest_all);
    $quest_all_values = array_values($quest_all);
    

    Or simply use foreach():

    $keys = [];
    $values = [];
    foreach($quest_all as $key => $value){
        $keys[] = $key;
        $values[] = $value;
    }
    

  • answered 2019-10-15 19:52 sssurii

    Try as below: One way is: array_values($quest_all); will give you an array of all Ids array_keys($quest_all); will give an array of all qcounters and respective indexes for qcounter and ids will be the same.

    Other way, First get all qcounters only from collection:

    $quest_all = $qwinners->pluck('qcounter')->toArray();
    $qcounter1= $quest_all[0];
    $qcounter2= $quest_all[1];
        ...
        and so on
    

    Then get all ids

    $quest_all = $qwinners->pluck('id')->toArray();
    $id1= $quest_all[0];
    $id2= $quest_all[1];
        ...
    and so on
    

    You can also use foreach to iterate through the result array.

  • answered 2019-10-16 06:26 lagbox

    I am not sure why you want variable names incrementing when you could have an array instead but if you don't mind an underscore, '_' in the name and them starting at 0 index you can use extract to create these variables. (As an exercise)

    $quest_all = ...;
    
    $count = extract(array_keys($quest_all), EXTRA_PREFIX_ALL, 'qcounter');
    extract(array_values($quest_all), EXTRA_PREFIX_ALL, 'id');
    // $qcounter_0 $qcounter_1
    // $id_0 $id_1
    
    
    for ($i = 0; $i < $count; $i++) {
        echo ${'qcounter_'. $i} .' is '. ${'id_'. $i} ."\n";
    }
    

    It would probably be easier to just have the 2 arrays:

    $keys = array_keys($quest_all);
    $values = array_values($quest_all);