0

I'm looking for a smart way to find out if my array of objects within an object has multiple name values or not to do a validation since it's only allowed to have one array name per inner array:

$elements = [];

$elements[18][20] = [
    [
        'name'  => 'Color',
        'value' => 'Red'
    ],
    [
        'name'  => 'Color',
        'value' => 'Green'
    ],
    [
        'name'  => 'Size',
        'value' => 'S'
    ]
];
$elements[18][21] = [
    [
        'name'  => 'Size',
        'value' => 'S'
    ],
    [
        'name'  => 'Length',
        'value' => '20'
    ],
];

error_log( print_r( $elements, true ) );

So the object 20 for example is invalid because it has 2 colors with the same value. At the end I was hoping to get a result array containing 1 duplicate name. This way I can output them like: "You have at least one duplicate name: Color".

My first idea was to loop over the array and do a second loop. This way it was possible to receive the inner arrays containing the stuff. Now I was able to add every name to another array. After this I was able to use count() and array_intersect() to receive a value of x which showed me if there are duplicates or not.

Now I had a count, but not the actual value to display. Before I use a semi-good solution, I was hoping to get any ideas here how I can make it better!

1 Answer 1

1

This loop will generate your expected output:

foreach($elements[18] as $index => $element){
    //Get all the elements' names
    $column_key = array_column($element, 'name');
    //Get the count of all keys in the array
    $counted_values = array_count_values($column_key);
    //Check if count is > 1
    $filtered_array = array_filter($counted_values, fn($i) => $i > 1);
    //If the filter is not empty, show the error
    if(!empty($filtered_array)){
        //get the key name
        $repeated_key = array_key_first($filtered_array);
        echo "You have at least one duplicate name: {$repeated_key} at index {$index}";
        break;
    }
}

It relies in the array_count_values function.

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

1 Comment

Thank you for your help. I actually used your logic to complete my function. Since I want to print out every duplicate, I've saved all $filtered_arrays to another array and returned it in case there is an error. This way I was able to get all the wrong values.

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.