Search code examples
phparraysmultidimensional-arraykeyisset

PHP isset multidimensional array, variable for key in first dimension of array


I have an array of arrays as follows (for example)

$array = (
    [0] => array (
        [a_key]     => 123456,
        [b_key]     => First Name,
        [c_key]     => Last Name,
        [this_key ] => Institution,
        ),
    [1] => array (
        [a_key]     => 123456,
        [b_key]     => First Name,
        [c_key]     => Last Name,
        [this_key ] => Institution,
        ),
    [2] => array (
        [a_key]     => 123456,
        [b_key]     => First Name,
        [c_key]     => Last Name,
        [this_key ] => Institution,
        ),
)

And I want to check if $array[$key]['this_key'] is not null or does not equal '' when

$key = (any number)

How do I set $key to match any number so that the following returns true when at least one second-dimension-array in the array has [this_key] set?

if( $array[$key]['this_key'] != '' )
    echo "true";
else 
    echo "false";

So, if $array[0][this_key] is not set, $array[1][this_key] IS set, and $array[2][this_key] is not set, the IF statement will return true because at least ONE of all of the arrays has [this_key] set.


Edit:

To give some context to the situation and provide a specific scenario to which this solution could be applied:

I have a list of people in a database that I need to display. For each person, I have a first and last name, and optionally an institution/degree/job title held by the individual. These need to display like this:

Without a title:
John Smith, Jane Doe, Fred Nerk

With a title:
John Smith, Penologist; Jane Doe, Professor; Fred Nerk, Astrophysicist

With mixed cases of a title:
John Smith; Jane Doe, Professor; Fred Nerk

Note the punctuation used in each case. If there is no optional information for ANY record, a comma separates the individuals. If there is optional information for ONE OR MORE records, a semicolon separates the individuals.

With the if statement, I would be able to determine if one of the individuals has optional information, even if every other individual does not.


By the way:

This PHP Sandbox Tool was incredibly useful for testing PHP code before integrating it into my file. It supports PHP versions from 4.4.9 up to 5.5.5.


Solution

  • For PHP >= 5.5.0, I used:

    if(array_filter(array_column($array, 'this_key'))){
        // true, do something
    }
    

    When this returns true, I know that at least one array has information in this_key, and so I can do something unique for this case.

    My server runs PHP 5.4.13, so I used the recommended userland implementation for PHP lower than 5.5. It was simple to implement, and it works as expected.