Search code examples
phparraysmultidimensional-arrayassociative-array

Catch the array inside another array


Let me show you an example of what I'm trying to do. I got this:

$array = [
[
    'first_name' => 'John',
    'last_name'  => 'Doe',
], 
[
    'first_name' => 'Johny',
    'last_name'  => 'Dow',
],  
[
    'first_name' => 'Johnys',
    'last_name'  => 'Doesnot',
], 
[
    'first_name' => 'Joe',
    'last_name'  => 'Dow',
], 
[
    'first_name' => 'Joes',
    'last_name'  => 'Down',
],
];

I want to catch the last array in which 'last_name' => 'Dow', and change all the data for this array (first_name and last_name) and maybe add the age.

I think that array_filter() can be helpful in this case but I'm not sure how to deal with it.

Can someone guide me how to achieve this.

Thank you!


Solution

  • Becase you want to catch the last item, so you can iterate from the end of array and then, break the loop after you catch the first item meets your condition:

    for ($i = count($array) - 1; $i >= 0; $i--) {
        if ($array[$i]["last_name"] == "Dow") {
            $array[$i]["first_name"] = "New First Name";
            $array[$i]["last_name"] = "New Last Name";
            $array[$i]["age"] = 111;
            break;
        }
    }