How to store each array value with their keys in php

82 views Asked by At

I want to store my variables in an array alongside their keys like :

filter : [ 
"0" : "test",
"1" : "you",
"2" : "php"
]

I have filter[] array in the first place and each time with update request I want to add a value to this array with it's key, automate created key.

I've tried this two methods but they are not storing variable keys:

//$seat_filters = filter array fetched from db

$filters = array($request->input('filter'));

$filters_array = array_merge($seat_filters, $filters);

When I check the result of $filters_array I get :

filter : [
"test",
"you",
"php"
]

Same thing happens in below method of storing values in array :

 array_push($seat_filters ,$request->input('filter'));

Only second method is shorter. FYI : This results are in JSON format.

3

There are 3 answers

2
u_mulder On BEST ANSWER

Though I don't understand what all these for, but still some advices.

So you have an array like:

$a = ["test","you","php"];
// though it's indexes are not visible - they exist
$filter = [];
// you can see indexes in this `foreach`
foreach ($a as $k => $v) {
    echo 'Key is ', $k, '; value is ', $v;
    // now you can add both values to your filter
    $filter[] = [$k, $v];
}
print_r($filter);
echo json_encode($filter); // [[0,"test"],[1,"you"],[2,"php"]]
0
LF-DevJourney On

To save your key in an array:

  $output = array_map(function($v, $k){return[$k, $v];}, $array);
1
Prasanna On

Try this method in php.

array_combine()