infinite
infinite

Reputation: 21

Finding key in array that meets conditions

I'm trying to extract a key from an array that meets some criteria and I'm having problems filtering this array. This is a sample and the array can have much more elements. They will all have the same country, region and prefix. What can be different is update_status and activation_date.

[0] => Array
    (
        [id] => 2
        [country] => Country
        [region] => Region
        [prefix] => 12345
        [new_rate] => 0.2000
        [update_status] => 
        [activation_date] => 
    )

[1] => Array
    (
        [id] => 4
        [country] => Country
        [region] => Region
        [prefix] => 12345
        [new_rate] => 0.2000
        [update_status] => NEW
        [activation_date] => 2014-10-03 03:48:00
    )

What I need to find is the FIRST occurrence (key) where update_status IS NOT EMPTY (if exists). If the key when status is not empty doesn't exist, i need the LAST occurrence where the status is empty.

Thanks a lot!

Upvotes: 1

Views: 103

Answers (2)

bwoebi
bwoebi

Reputation: 23777

$key = 0;
foreach ($array as $key => $value) {
    if ($value["update_status"] != "") {
        break;
    }
}

$key will contain first the occurrence (or the last element of the array if it doesn't exist)

(If a foreach loop ends, the $key and $value still have the values of the last iteration, so no problem.)

Upvotes: 1

Diogo Silva
Diogo Silva

Reputation: 311

$index = count($ARRAY) - 1;
foreach($ARRAY as $key=>$val){
    if(isset($val['update_status']) && !is_null($val['update_status'])){
        $index = $key;
        break;
    }
}

Does this work?

Upvotes: 1

Related Questions