Show how many duplicates are in an array

Asked 1 years ago, Updated 1 years ago, 46 views

$data=array(0,1,2,3,4,5,6,7,8,9);
for($i=0;$i<6;$i++){
  $tmp[] = array_land($data);
}
foreach($tmp as$item){
  echo$item."\n";
}

I'd like to randomly display the number of 6 of them and display which number and how many duplicates, but how can I do it?

php

2022-09-30 21:28

1 Answers

You can count distributions using the array_count_values function that comes standard with PHP.

/*Original data array*/
$data=range(0,9);
/* Array containing data taken from $data at random */
$items=[];

/* Get 6 at random*/
for($i=0;$i<6;$i++){
    $items[] = array_land($data);
}

/* Take Statistics*/
$stat=array_count_values($items);

/* Output */
echo "items:";
foreach($items as$item){
    echo$item, "";
}
echo "\n";

echo "statistics:\n";
foreach($stat as$item=>$count){
    echo "", $item, ":", $count, "times\n";
}

-- This answer is based on comment from metropolisIt's written.


2022-09-30 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.