-1

I have varieties of keys assume 10 in array and i care about only 3 keys

non empty keyA or non empty keyB or non empty keyC

the keys will always be present, but they may be empty, i just care about any of the above 3 keys which is not empty.

if any one of the 3 keys exists(first no matter which one) and is not empty , break the loop and get the key.

//example for KeyA 
if (array_key_exists("keya", $array) && !empty($array['keya'])) {
return keya;
break;
}

is there a way to do it in elegant/advised/optimized way

MikasaAckerman
  • 531
  • 5
  • 17
  • Possible duplicate of [Remove empty array elements](https://stackoverflow.com/questions/3654295/remove-empty-array-elements) – Alister Bulman Apr 24 '18 at 22:26

1 Answers1

3

This one is quite easy with some of the advanced array handling, and particularly array_filter - even without a custom callback.

<?php
$x = [ 'a' => '', 'b' => '', 'c' => 'x' ];
var_dump(array_filter($x));

As described on array_filter, if no callback function is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. That includes the boolean FALSE, 0 (int and float), the empty string, and the string "0", arrays with zero elements and NULL.

Results:

array(1) {
  ["c"]=>
  string(1) "x"
}

When you have all the non-empty values, getting the first one, is also easy, with current().

Alister Bulman
  • 34,482
  • 9
  • 71
  • 110
  • I have edited the question to , mention that there might be more than three keys – MikasaAckerman Apr 24 '18 at 22:42
  • Is there not a built-in function that considers 0 to be set/non-empty but an empty string to be empty? It looks like `empty` isn't kind to 0, while `isset` treats an empty string as non-empty. – Anthony Apr 24 '18 at 22:51