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

Time:07-02

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.

CodePudding user response:

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
}

CodePudding user response:

is just a simple foreach

<?php

$test=
[
  "name" => "user"
  ,0 => "created_at"
  ,"email" => "mail"
];

$res=[];
foreach(array_keys($test) as $ch){
    (is_numeric($ch) and ($res[]=$test[$ch])  )or ($res[]=$ch);
}
var_dump($res);

?>
  •  Tags:  
  • php
  • Related