update page now

Voting

: min(five, zero)?
(Example: nine)

The Note You're Voting On

Rumour
2 years ago
If you want to preserve the array keys AND you want it to work on both object properties and array elements AND you want it to work if some of the arrays/objects in the array do not have the given key/property defined, basically the most ROBUST version you can get, yet quick enough:

<?php
function array_column_keys(array|ArrayAccess $arr, string $col) {
    // like array_columns but keeps the keys
    //to make it work for objects and arrays
    
    return array_map(fn($e) => (is_countable($e) ? ($e[$col]??null) : null) ?: (is_object($e) ? $e->$col : null), $arr);
}

?>

If a key/property is undefined, the value in the result array will be NULL. You can use array_filter() to filter those out if needed.

<?php

class a {
   public string $a = 'property a';
   public string $b = 'property b';
}

$a1 = new a;
$a2 = new a;
$a2->a = 'plop';

$b = ['one'=> ['a'=>'plop'], 
      3    => $a1, 
      4    => $a2, 
      5    =>[],
      'kud'=>new a];

return array_column_keys($b, 'a');

?>

Returns:

Array
(
    [one] => plop
    [3] => property a
    [4] => something else
    [5] => 
    [kud] => property a
)

<< Back to user notes page

To Top