I’ve just come across a problem, which apparently looks simple, but I can’t find a solution. I have the following array in PHP:
[
"name" => "user"
0 => "created_at"
"email" => "mail"
]
And I need to get an array like this:
[
"name"
"created_at"
"email"
]
As you can see, I only need to obtain the original keys from the array, but in case a value from the original array does not have an associated value, then return the value instead of the key.
I have tried several ways using the following methods:
array_flip()
array_keys()
array_values()
I would appreciate in advance anyone who could help me.
>Solution :
Loop through the array and add the desired values to your new array:
$a = [
"name" => "user",
0 => "created_at",
"email" => "mail",
];
$b = [];
foreach ( $a as $k => $v ) {
$b[] = ( $k ? $k : $v );
}
print_r($b);
/*
Array
(
[0] => name
[1] => created_at
[2] => email
)
*/
For a more sophisticated determination of which key(s) to keep, replace the first $k in the ternary expression with a function that tests $k for validity:
$b[] = ( test($k) ? $k : $v );
// ...
function test($k) {
return ! is_number($k); // For example
}