0

I'm a very beginner php worker who just got to know Stackoverflow.

My requirement is to select the largest value inside the nested array. Let me explain with an example.

$arr = [
    ["id"=>1],
    ["id"=>2],
    ["id"=>2],
    ["id"=>2],
    ["id"=>3],
    ["id"=>4],
    ["id"=>4],
    ["id"=>4]
];

In this array, we have the number 2 and 4, which are repeated the most.

What functions can I use to do this?

4 Answers 4

1

You can leverage array_count_values.

<?php

$data = [
    ["id"=>1],
    ["id"=>2],
    ["id"=>2],
    ["id"=>2],
    ["id"=>3],
    ["id"=>4],
    ["id"=>4],
    ["id"=>4]
];

$ids       = array_column($data, 'id', null);
$id_counts = array_count_values($ids);
$max_ids   = array_keys($id_counts, max($id_counts));
var_export($max_ids);

Output:

array (
  0 => 2,
  1 => 4,
)
Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this:-

<?php

$arr = [
    ["id"=>1],
    ["id"=>2],
    ["id"=>2],
    ["id"=>2],
    ["id"=>3],
    ["id"=>4],
    ["id"=>4],
    ["id"=>4]
];

$repeatedArr = array();

foreach($arr as $key => $data) {
    foreach($data as $id => $value) {
        if(array_key_exists($value, $repeatedArr)) {
            $repeatedArr[$value]++;
        } else {
            $repeatedArr[$value] = 1;
        }
    }
}

foreach($repeatedArr as $key => $value) {
    echo $key . " is repeated " . $value . " times\r\n";
}

Comments

0

This would be an approach:

<?php
$data = [
    ["id"=>1],
    ["id"=>2],
    ["id"=>2],
    ["id"=>2],
    ["id"=>3],
    ["id"=>4],
    ["id"=>4],
    ["id"=>4]
];
$counts = [];
array_walk($data, function($entry) use (&$counts) {
    $counts[$entry["id"]]++;
});
var_dump($counts);

The output obviously is:

Array
(
    [1] => 1
    [2] => 3
    [3] => 1
    [4] => 3
)

Comments

0

As you asked to "select the largest value"...

If you want to return the array holding the largest value...

max($arr)

will return ["id"=>4]

If you want only the value returned...

array_values(max($arr))[0]

will return (int)4

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.