Jimmy Adaro
Jimmy Adaro

Reputation: 1405

Find partial string inside array

I have this array from an AJAX request:

array (
    [0] => 'lat,long@id_1'
    [1] => 'lat,long@id_2'
    [2] => 'lat,long@id_3'
)

The problem here is I'm not gonna have always a 'correct-ordered' array like that, so it may look like this one:

array (
    [0] => 'lat,long@id_1'
    [1] => 'lat,long@id_2'
    [2] => 'lat,long@id_3'
    [3] => 'lat,long@id_1'
    [4] => 'lat,long@id_3'
    [5] => 'lat,long@id_2'
)

I need to get the last array value of every id_X (currently only 3 ids):

array (
    [3] => 'lat,long@id_1'
    [4] => 'lat,long@id_3'
    [5] => 'lat,long@id_2'
)

How can I find each last value of that array based on partial string (id_X)?

Upvotes: 0

Views: 35

Answers (1)

Markus AO
Markus AO

Reputation: 4889

First do a reverse sort to ensure the latest values are parsed first. Then run them through a loop, matching the partial string to get the ID, adding the data to an array if the ID index doesn't exist yet. Last values will be added to your array, others will be neglected. Something like this:

rsort($ajaxy);

$lasts = [];

foreach($ajaxy as $str) {
    $id = substr($str, strrpos($str, '@') + 1);
    if (!isset($lasts[$id])) {
        $lasts[$id] = $str; 
    }
}

var_dump($lasts);

If you have a huge array, and you know the amount of IDs you will be getting, you can add in a check to terminate the loop when all required IDs have been added in to avoid redundant processing.

Otherwise, don't bother with the reverse sort, and simply keep overwriting previous values 'til the end, but I find this a cleaner approach. ^_^

Upvotes: 1

Related Questions