Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all the keys of an array and in case the key has no value, return the value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading