1

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]);
            }
        }
0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the detailed answer. Also appreciate for alternative method!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.