-4

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!

Marinario Agalliu
  • 989
  • 10
  • 25

2 Answers2

1

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;
    }
}
Kien Nguyen
  • 2,616
  • 2
  • 7
  • 24
1

Alternatively you can iterate over the array with array_reverse. Setting the flag to true will preserve the keys, allowing us to access the corresponding item by its index.

foreach (array_reverse($array, true) as $index => $person) {
    if ($person['last_name'] == 'Dow') {
        // $array[$index]['first_name'] = 'some name';
        // $array[$index]['last_name'] = 'some name';
        $array[$index]['age'] = 25;

        break;
    }
}

echo '<pre>';
print_r($array);
echo '</pre>';

Output:

Array
(
    [0] => Array
        (
            [first_name] => John
            [last_name] => Doe
        )

    [1] => Array
        (
            [first_name] => Johny
            [last_name] => Dow
        )

    [2] => Array
        (
            [first_name] => Johnys
            [last_name] => Doesnot
        )

    [3] => Array
        (
            [first_name] => Joe
            [last_name] => Dow
            [age] => 25
        )

    [4] => Array
        (
            [first_name] => Joes
            [last_name] => Down
        )

)
Remy
  • 777
  • 2
  • 8
  • 15