Reputation: 420
Please could someone help find a better solution to the code below.
Here is my existing solution:
$list = '54,78,3,5';
$list = explode(",",$list);
foreach($list as $k => $v) { $compare[$v] = 1; }
when i run array_flip instead of the foreach on $list it returns an array like this:
Array(
54 => 0,
78 => 1,
...
)
I need this so another array which is already in this format can be compared with an IF statment:
Array(
54 => 1,
78 => 1,
...
)
Upvotes: 2
Views: 48
Reputation: 4783
Do you need the original $list
to be a variable? Can't you just make it an array from the start wherever the data comes from, and append 1 or true to the value?
Otherwise, before your current foreach
, add a new loop and go through $list
(which you made into an array) and make a new array appending the required value to each key (keys taken from $list
):
foreach ($list as $key)
{
$new_array[$key] = 1;
}
Upvotes: 0
Reputation: 219864
$list = '54,78,3,5';
$list = explode(",",$list);
$array = array_combine($list, array_fill(0, count($list), 1));
print_r($array);
Array
(
[54] => 1
[78] => 1
[3] => 1
[5] => 1
)
array_fill()
will create an array with all of its values being the number 1
at the same size as the $list
array. array_combine()
then creates a new array with the values of $list
as the keys and the values created by array_fill()
;
Upvotes: 2