justsimpleuser
justsimpleuser

Reputation: 169

Delete array from nested array

How can I delete the first Name arrray

    [0] => Array
        (
            [Name] => John

        )

from this one just if exist at lest two Name objects?

Array
(
    [0] => Array
        (
            [Name] => John

        )

    [1] => Array
        (
            [Name] => James

        )

    [2] => Array
        (
            [Surname] => Doe

        )
)

I'm trying to go through array with foreach, count how many arrays has name object and if there is more than one, then unset the first, but I'm not able to do that:

        foreach($endArray as $arr)
        {
            if(count($arr['Name'])>1)
            {
                unset($endArray[0]);
            }
        }

Upvotes: 1

Views: 63

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

In your code you use if(count($arr['Name'])>1) but I think that will never be true as the count will return 1 when the value is neither an array nor an object with implemented Countable interface.

To unset the first when there are more than one, you could count the number of occurrences of "Name" in the items using array_column.

If you want to remove the first array which has a key "Name" you could loop over the items and use unset using the $key.

Then break the loop to only remove the first encounter item.

$endArray = [
    ["Name" => "John"],
    ["Name" => "James"],
    ["Name" => "Doe"]
];

if (count(array_column($endArray, 'Name')) > 1) {
    foreach ($endArray as $key => $arr) {
        if (array_key_exists('Name', $arr)) {
            unset($endArray[$key]);
            break;
        }
    }
}

print_r($endArray);

Php demo

Output

Array
(
    [1] => Array
        (
            [Name] => James
        )

    [2] => Array
        (
            [Name] => Doe
        )

)

Another option is to keep track of the number of times the "Name" has been encountered:

$count = 0;

foreach ($endArray as $key => $arr) {
    if (array_key_exists('Name', $arr) && $count === 0) {
        $count++;
    } else {
        unset($endArray[$key]);
        break;
    }
}

Php demo

Upvotes: 1

Related Questions