2

I'm trying to find when the array has 2nd dimension values that are the same so I can deal with them.

I've looked at array_unique and other people who are asking a similar question, but they all delete the values instead of returning them.

Say I have an array like this:

array(
    [0] => array(
        [laps] => 7,
        [corrected_time] => 18
    ),
    [1] => array(
        [laps] => 6,
        [corrected_time] => 18
    ),
    [2] => array(
        [laps] => 7,
        [corrected_time] => 18.5
    )
)

I'd like to have it return: array(0,1) because they both have the same value for corrected time

3
  • wait. Is it only grabbed if corrected_time is repeated? Commented Nov 10, 2016 at 19:31
  • 1
    how about array_unique to remove duplicates, then array_diff to get the values removed? Commented Nov 10, 2016 at 19:38
  • @Jay Yes, sorry for not making this clear, I've updated the question Commented Nov 10, 2016 at 20:05

1 Answer 1

2

Here is one approach. First get the values for corrected_time and convert them to strings (because we'll use them in array_count_values, which only works on ints and strings).

$times = array_map('strval', array_column($your_array, 'corrected_time'));

Then find all the values that occur more than once using array_count_values and array_filter.

$repeats = array_filter(array_count_values($times), function($time) {
    return $time > 1;
});

After you have this list of repeated times, you can use it to filter your original array to only include items with repeated times.

$multiples = array_filter($your_array, function($item) use ($repeats){
    return isset($repeats[(string) $item['corrected_time']]);
});

You can iterate over this, or if you only want the keys, you can get them with

$keys = array_keys($multiples);
Sign up to request clarification or add additional context in comments.

3 Comments

this seems a lot more complicated than the other answer
Have you tested the other answer with a larger set of values to see if it really does what you need it to? It appears to me that it only coincidentally works for the example from your question.
You are correct, I've done some tests and found the other answer doesn't complete the task suitably.

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.