You can use values as temporary keys, so long as the $something
array does not contain:
- non-scalar values (objects/arrays/etc. cannot be used as keys) or
- values that will be mutated when used as an array keys (floats get truncated, nulls become empty strings, and booleans become ints)
- a mix of numeric strings and integers that will be loosely evaluated as equal (
2
vs "2"
)
(Bad Demo)
Code: (Good Demo)
$something = [3, 2, 1, 3, 6, 5, 1, 1];
$liste = [];
foreach ($something as $value) {
$liste[$value] = $value;
}
Output:
array (
3 => 3,
2 => 2,
1 => 1,
6 => 6,
5 => 5,
)
The above will absolutely perform better than any other approach on this page that is using a duplicate-checking technique. PHP will not allow duplicated keys on any single level of an array, so it will merely overwrite a re-encountered value.
If the new keys do not impact future processing, leave them as they are, otherwise call array_values()
to re-index the array.
$value
is. Is it a scalar value? Is it consistently an integer? a string? Depending on this vital detail, there may be more efficient ways than to make iterated calls ofin_array()
. – Eustashe