PHP Array Keep Data and Calculating By Its Index - php

I have a list of number in array. Here's my example data:
Person 1 => 20, 40, 50
Person 2 => 10, 20, 40
Person 3 => 20, 20, 30
I want to ask, how to put their scores to an array and calculate it by it index? My code to create this array:
$indeksarr = 1;
$temparr[$indeksarr] = array();
$num = 3;
while($grade = $query->fetch_array()) <-- basically get score from DB (only return score for each student)
{
for($i=1; $i <= $num; $i++)
{
$newdata = array($indeksarr => $grade);
$temparr[$indeksarr][] = $newdata;
$indeksarr++;
}
}
for($i=1; $i <= $num; $i++)
{
print_r($temparr[$i]);
}
My code result:
Result[1] = 20
Result[2] = 10
The result that I want:
Result[1] = 50 ( <- 20+10+20 ) <- all from array index 1
Result[2] = 80 ( <- 40+20+20 ) <- all from array index 2
Result[3] = 120 ( <- 50+40+30 ) <- all from array index 3
Any idea to fix my array?

Please try below code once, it might help for dynamic values also.
while ($grade = $query->fetch_array()) {
//$grdata = explode(",", $grade); // if those are comma separated values
$grdata = $grade;
for ($j = 0, $k = 1; $j < count($grdata); $j++, $k++) {
if (isset($temparr[$k])) {
$temparr[$k] = $temparr[$k] + $grdata[$j];
} else {
$temparr[$k] = $grdata[$j];
}
}
}
print_r($temparr);

biuld array like below
$persons = array('Person1'=>array(20,40,50),'Person2' => array(10, 20, 40),'Person3' => array(20, 20, 30));
//than perform below function
$array_sum = array_reduce($persons,"abb");
function abb($a,$b)
{
foreach($b as $key=>$value)
{
if(isset($a[$key]))
$a[$key] += $value;
else
$a[$key] = $value;
}
return $a;
}
var_dump($array_sum);
o/p
array (size=3)
0 => int 50
1 => int 80
2 => int 120

try this:
$result = array();
$start_index = 1;
$stop_index = 3;
while($grade = $query->fetch_array()) //<-- basically get score from DB (only return score for each student)
{
// grade = array('Person 1' => array(20,10,20));
$values = array_values($grade);
$result[$start_index] = array_sum($values[0]);
if ($start_index == $stop_index) break; // stop when it reach stop_index
$start_index++;
}
echo "<pre>";
print_r($result);
echo "</pre>";
die;

Here's a simple alternative using array_walk and array_sum:
$subTotal = [[0,0,0],[0,0,0],[0,0,0]];
$line = 0;
function walk($item, $key) {
global $subTotal;
global $line;
$subTotal[$key][$line] = $item;
}
$array = [
[20, 40, 50],
[10, 20, 40],
[20, 20, 30]
];
$finalArray = [];
array_walk($array[0], 'walk');
$line = 1;
array_walk($array[1], 'walk');
$line = 2;
array_walk($array[2], 'walk');
$finalArray[] = array_sum($subTotal[0]);
$finalArray[] = array_sum($subTotal[1]);
$finalArray[] = array_sum($subTotal[2]);
// Will print '50, 80, 120, '
foreach($finalArray as $total) {
echo $total.', ';
}
Hope this helps!

Related

How do I solve this problem statement using PHP?

Suppose a number is given which is of positive integer type, e.g: 312. Please help me to write a program in PHP which convert that given number to a new number having same number of digits and all the digits of the new number must be equal to any of the digits of the given number (e.g: 333, 111, 222 by either decrementing or incrementing each digit by 1 at a time only). But print only that sequence of digits which takes lesser number of steps to generate the sequence and also print the number of steps taken to generate that sequence.
Explanation:
Input: A positive integer N (e.g: 312)
converting the number(312) to the sequence of 3
3 2 2
3 3 2
3 3 3
here number of steps = 3
Now, converting the number(312) to the sequence of 1
2 1 2
1 1 2
1 1 1
here number of steps = 3
and finally converting the number(312) to the sequence of 2
2 1 2
2 2 2
here number of steps = 2
So, Output: 222
Number of steps: 2
Here's what I tried but lost
<?php
$num = 312;
$arr_num = array_map('intval', str_split($num));
//steps taken for each sequence will be stored in this array
$steps = array();
//printing number
for($i = 0; $i < count($arr_num); $i++)
echo $arr_num[$i];
//calculation
for($i = 0; $i < count($arr_num); $i++) {
$count = 0;
for($j = 0; $j < count($arr_num); $j++) {
if($arr_num[$i] == $arr_num[$j])
++$j;
elseif($arr_num[$i] > $arr_num[$j]) {
while($arr_num[$j] != $arr[$i]) {
$arr_num[$j] += 1;
$count++;
}
}
else {
while($arr_num[$j] != $arr_num[$i]) {
$arr_num[$j] -= 1;
$count++;
}
}
}
//pushing the count to steps array for each sequence
array_push($steps, $count);
}
//I am stuck here...can't find the further solution
?>
This works (according to my very quick testing)):
$intIn = 312;
# function changeDigits( $intIn ) { // uncomment for function
$digits = str_split( $intIn ); // convert to array of digits
$numerOfDigits = count($digits);
$numberOfSteps = array();
# check each digit in number
for ($i=0; $i < $numerOfDigits; $i++) {
$numberOfSteps[$i] = 0;
$currentDigit = $digits[$i];
# count the number of inc/decrements to change the other digits to this digit
foreach($digits as $otherDigit) {
if ($currentDigit > $otherDigit) $numberOfSteps[$i] += $currentDigit - $otherDigit;
if ($currentDigit < $otherDigit) $numberOfSteps[$i] += $otherDigit - $currentDigit;
}
}
$digitKey = array_search( min($numberOfSteps), $numberOfSteps );
echo 'Number of Steps: ' . $numberOfSteps[$digitKey] . PHP_EOL; // (or '<br>')
echo 'New number = ' . str_repeat( $digits[$digitKey], $numerOfDigits );
#}
# changeDigits(312);
Demo
I devepled this code. please have a look once
<?php
function find_output($input)
{
$digits = str_split($input);
foreach ($digits as $index => $d) {
$new_array = $digits;
unset($new_array[$index]);
$sum = 0;
foreach ($new_array as $value) {
$sum += abs($d - $value);
}
$final_array[$d] = $sum;
}
$steps = min($final_array);
echo "steps : " . $steps . '<br>';
$final_value = array_search(min($final_array), $final_array);
echo "Output: " . implode(array_fill(0, count($digits), $final_value));
}
find_output(819);
?>
<?php
class SeqSolver
{
public function solve($str_num)
{
if(!ctype_digit($str_num))
throw new Exception('Invalid input. Input string must contain digits between 0 and 9 only.');
$digits = str_split($str_num);
$length = count($digits);
foreach(array_unique($digits) as $digit)
$results[$digit] = $this->stepsToSequence($str_num, $digit);
//var_export($results);
$min_keys = array_keys($results, min($results));
// Prepare result
$result['input'] = $str_num;
foreach($min_keys as $key)
$result['solutions'][] = [
'sequence' => str_repeat($key, $length),
'steps' => $results[$key]
];
return $result;
}
public function stepsToSequence($str_num, $target_digit) {
$digits = str_split($str_num);
$steps = 0;
foreach($digits as $digit)
$steps += abs($digit - $target_digit);
return $steps;
}
}
Example use:
$solver = new SeqSolver;
foreach(['312', '334', '39'] as $input) {
$result = $solver->solve($input);
var_export($result);
echo "\n";
}
Output:
array (
'input' => '312',
'solutions' =>
array (
0 =>
array (
'sequence' => '222',
'steps' => 2,
),
),
)
array (
'input' => '334',
'solutions' =>
array (
0 =>
array (
'sequence' => '333',
'steps' => 1,
),
),
)
array (
'input' => '39',
'solutions' =>
array (
0 =>
array (
'sequence' => '33',
'steps' => 6,
),
1 =>
array (
'sequence' => '99',
'steps' => 6,
),
),
)
I think this will do the job.
<?php
$input = 312;
$input_array = [];
for($x=0;$x<3;$x++) {
array_push($input_array,strval($input)[$x]);
}
function equalize($input_array, $mark) {
$i = 0;
for($x=0;$x<count($input_array);$x++) {
$input_array[$x] = intval($input_array[$x]);
#print($input_array[$x]);
while($input_array[$x] != $mark) {
if($input_array[$x] < $mark) {
$input_array[$x] = $input_array[$x] + 1;
$i++;
}
else {
$input_array[$x] = $input_array[$x] - 1;
$i++;
}
}
}
$output_val = intval($input_array[0] .$input_array[1] .$input_array[2]);
return $output = [$output_val,$i];
}
#to first
$mark = $input_array[0];
$output = equalize($input_array, $mark);
#to second
$mark = $input_array[1];
$data = equalize($input_array, $mark);
if($data[1] < $output[1]) {
$output = $data;
}
#to last
$mark = $input_array[2];
$data = equalize($input_array, $mark);
if($data[1] < $output[1]) {
$output = $data;
}
echo 'Digit: ' .$output[0] .'<br/>';
echo 'Number of steps: ' .$output[1];
?>

How to condense an array of integers in PHP?

So I have an array of integers: <1, 2, 3, 9, 10, 11, 14>, that I would like to join together in this format: <1-3, 9-11, 14>.
I'm new to PHP and tried doing this by looping through the array:
function pasteTogether($val)
{
$newVals = array();
$min = $val[0];
$max = $val[1];
$counter = 0;
for ($i = 0; $i < count($val); $i++)
{
if ($val[$i + 1] === $val[$i] + 1)
{
$max = $val[$i + 1];
}
else
{
$tempVal = $min."-".$max;
$newVals[$counter] = $tempVal;
$counter++;
$min = $val[$i];
}
}
return $newVals;
}
However, when I run this code, I get <1-3, 3-11, 11-11, 14-14>
PHP Fatal error: Maximum execution time of 30 seconds exceeded in ../learning.php on line 36
Because the for loop never ends you increment $val instead of $i
$array = array(1, 2, 3, 9, 10, 11, 14);
function pasteTogether($val)
{
$newVals = array();
$min = $val[0];
$max = $val[1];
$counter = 0;
for ($i = 0; $i < count($val); $i++)
{
if ($val[$i + 1] === $val[$i] + 1)
{
$max = $val[$i + 1];
}
else
{
$tempVal = $min."-".$max;
$newVals[$counter] = $tempVal;
$counter++;
$min = $val[$i];
}
}
return $newVals;
}
pasteTogether($array);
I have been playing around with this interesting problem and found another solution. So, if anyone is interested:
$arr=array(1, 2, 3, 9, 10, 11, 14, 15, 16, 18);
$v0=$dif=null;$rows=array();
foreach ($arr as $i => $v) {
if ($dif!=($d=($v-$i))){
if ($v0) $rows[]="$v0-".$arr[$i-1];
$v0=$v;
$dif=$d;
}
}
$rows[]="$v0-".($d==$dif?$arr[$i]:$v0);
print_r($rows);
I added a few numbers to the array and the result is this:
$rows = Array
(
[0] => 1-3
[1] => 9-11
[2] => 14-16
[3] => 18-18
)
You can find a little demo here: http://rextester.com/ABC25608
This works:
function pasteTogether($val)
{
$compacted = [];
$min = null;
$max = null;
$format = function ($a, $b) {
return ($a < $b ? "$a-$b" : $a);
};
foreach ($val as $current) {
if ($min === null) {
$min = $current;
$max = $current - 1;
}
if ($current == $max + 1) {
$max++;
} else {
$compacted[] = $format($min, $max);
$min = $current;
$max = $current;
}
}
$compacted[] = $format($min, $max);
return $compacted;
}
echo '<', implode(', ', pasteTogether([1, 2, 3, 9, 10, 11, 14])), '>';
Output:
<1-3, 9-11, 14>

Find key of array based on variable value between array values [duplicate]

This question already has answers here:
Find a matching or closest value in an array
(13 answers)
Closed 7 years ago.
I need to find the left-near key of a base array corresponding to a variable value.
Searched value (in this case) is always between 1 and 779
Better with an example:
$fixedArr = [ 0, 5, 8, 20, 40, 60, 90, 135, 780 ];
$search = 42; // $result = $arr[4] -> 4;
$search = 110; // $result = $arr[6] -> 6;
$search = 134; // $result = $arr[6] -> 6;
$search = 135; // $result = $arr[7] -> 7;
I try with a foreach loop but with no luck, any idea??
Thanks
searched value is always between (in this case) 1 and 779
$fixedArr = [ 0, 5, 8, 20, 40, 60, 90, 135, 780 ];
$search = 42;
for ($i = 0; $i < count($fixedArr); $i++)
if ($search < $fixedArr[$i]) break;
echo $i-1;
This maybe help you;
$fixedArr = [ 0, 5, 8, 20, 40, 60, 90,135,780 ];
//
$search = 111; // $result = $arr[4] -> 4;
//$search = 110; // $result = $arr[6] -> 6;
//
function leftORright($fixedArr,$search){
$max = max($fixedArr)+1;
$near = array(
'left'=>array('key'=>'none','value'=>'none','bool'=>false),
'right'=>array('key'=>'none','value'=>$max,'bool'=>false),
'center'=>array('key'=>'none','value'=>'none','bool'=>false)
);
foreach($fixedArr as $k=>$v){
if($v == $search){
$near['center']['key'] = $k;
$near['center']['value'] = $v;
}
if($v < $search){
$near['left']['key'] = $k;
$near['left']['value'] = $v;
}
if($v > $search and $near['right']['value'] > $v){
$near['right']['key'] = $k;
$near['right']['value'] = $v;
}
}
//decide near left or right
$respright = $near['right']['value'] - $search;
$respleft = $search - $near['left']['value'] ;
$right_left_equals = false;
if($near['center']['value'] !== 'none'){
$near['center']['bool'] = true;
}else if($respleft < $respright && $near['left']['key']!='none'){
$near['left']['bool'] = true;
}else if($respleft > $respright && $near['right']['key']!='none'){
$near['right']['bool'] = true;
}else if($near['center']['value'] != 'none'){
$near['center']['value'] = true;
}else{
$right_left_equals = true;
}
//var_dump($near);
//Result is:
foreach($near as $k=>$v){
foreach($v as $k2=>$v2){
if($v2===true){
var_dump('near is for '.$k);
return $v;
}
}
}
//equal for right and left
if($right_left_equals){
var_dump('near right left are equals');
return array($near['right'],$near['left']);
}
}
$result = leftORright($fixedArr,$search);
var_dump($result);
response:
string 'near is for left' (length=16)
array (size=3)
'key' => int 6
'value' => int 90
'bool' => boolean true
Use array_search:
array_search — Searches the array for a given value and returns the corresponding key if successful
$search = array_search(42, $fixedArr); // -> 4
$search = array_search(110, $fixedArr); // -> 6
Your question is similar to finding the closest one:
<?php
$fixedArr = [ 0, 5, 8, 20, 40, 60, 90, 135, 780 ];
function getClosest($search, $arr) {
$left = 0;
foreach ($arr as $val) {
if ($search > $val)
$left = $val;
elseif ($search < $val) {
$right = $val;
break;
}
else {
$right = $val;
break;
}
}
return array($left, $right, array_search($left, $arr), array_search($right, $arr), (($search - $left) > ($right - $search) ? array_search($right, $arr) : array_search($left, $arr)));
}
print_r(getClosest(4, $fixedArr));
?>
Try this : It will Work in all cases.
$fixedArr = [ 0, 5, 8, 20, 40, 60, 90, 135, 780 ];
$find = 14;
for ($i=0; $i < count($fixedArr); $i++) {
if($fixedArr[$i] <= $find){
$large[] = $fixedArr[$i];
}else{
$small[] = $fixedArr[$i];
}
}
$near1 = max($large);
$near2 = min($small);
echo "Value $find coming in between $near1 and $near2";
echo "<br>";
if($find >= ($near1 + $near2) / 2){
echo "Closed Value is : $near2";
}else{
echo "Closed Value is : $near1";
}
Output:
Value 14 coming in between 8 and 20
Closed Value is : 20

Duplicate values multi array

As the title states I'm searching for a unique solution in multi arrays. PHP is not my world so I can't make up a good and fast solution.
I basically get this from the database: http://pastebin.com/vYhFCuYw .
I want to check on the 'id' key, and if the array contains a duplicate 'id', then the 'aantal' should be added to each other.
So basically the output has to be this: http://pastebin.com/0TXRrwLs .
Thanks in advance!
EDIT
As asked, attempt 1 out of many:
function checkDuplicates($array) {
$temp = array();
foreach($array as $k) {
foreach ($array as $v) {
$t_id = $k['id'];
$t_naam = $k['naam'];
$t_percentage = $k['percentage'];
$t_aantal = $k['aantal'];
if ($k['id'] == $v['id']) {
$t_aantal += $k['aantal'];
array_push($temp, array(
'id' => $t_id,
'naam' => $t_naam,
'percentage' => $t_percentage,
'aantal' => $t_aantal,
)
);
}
}
}
return $temp;
}
How about this code, each 'aantal' has initial value of 1, and duplicated id have their aantal incremented mutually, and duplicated id's are not suppressed. As your first array index is 0-based numeric, so we don't consider this dimension as a hash array, but rather a normal array.
UPDATED: id's can be duplicated 2 times, 3 times, 4 times, ...
<?php
//
// duplicate elements are not suppressed:
//
function checkDuplicates($xarr) {
//
$xarrDone = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
$xarrDone[$i] = true;
for($j = 0; $j < $n1; $j++)
{
$xarr[$hasId0[$j]]['aantal'] += $n1;
$xarrDone[$hasId0[$j]] = true;
}
}
}
}
//
return $xarr;
}
//
// duplicate elements are suppressed:
//
function checkDuplicates2Unique($xarr) {
//
$xarrDone = array();
$xarrNew = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
for($j = 0; $j < $n1; $j++)
{
$xarrDone[$hasId0[$j]] = true;
}
}
$xarrNew[] = $xarr[$i];
$xarrDone[$i] = true;
}
}
//
return $xarrNew;
}
//
// main test:
//
$xarr0 = array(
array(
'id' => 6
, 'naam' => 'Aardmonnik'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel 8 Bruin'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 3
, 'naam' => 'IV Saison'
, 'percentage' => '6,5%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => '3 Schténg'
, 'percentage' => '6,00%'
, 'aantal' => 1
)
);
//
echo "<pre>
Original:
";
print_r($xarr0);
//
echo "</pre>";
//
$xarr = checkDuplicates($xarr0);
//
echo "<pre>
Modified:
";
print_r($xarr);
//
$xarr = checkDuplicates2Unique($xarr0);
//
echo "<pre>
Modified Unique:
";
print_r($xarr);
//
echo "</pre>";
?>
?
checkDuplicates(): keep duplicated id's.
checkDuplicates2Unique(): delete duplicated id's to get unique id's.
Try using php's array_unique function: http://php.net/manual/en/function.array-unique.php
It should work on arrays
Otherwise (if you can sort the array -> faster):
<?php
$db = array(....); // your data
function remove_duplicates (array $arr) {
usort($arr, function ($a, $b) {
return $a['id'] < $b['id'];
});
$result = array();
$last_id = null;
$last_index = -1;
for ($i=0; $i<count($arr); ++$i) {
if ($arr[$i]['id'] == $last_id) {
result[$last_index]['aantai'] += 1;
continue;
}
$last_id = $arr[$i]['id'];
$last_index = count($result);
$result[] = $arr[$i];
}
return $result;
}
?>
Only loop over the input once, then copy the element when the id is new, else add the value:
function checkDuplicates($array) {
$temp = array();
// Only loop through the input once
foreach($array as $k) {
// Use the id as array index
if (array_key_exists($k['id'], $temp) {
// Only check id and add aantal?
$temp[$k['id']['aantal'] += $k['aantal'];
} else {
// Copy the element to the output
$temp[$k['id']] = $k;
}
}
return $temp;
}
Depending on your further code, you might need to reset the array indices by sort() or something.
Edit: sorry I forgot an index to $temp - the aantal field schould be correct now.

Getting the most repeated values in an array [duplicate]

This question already has answers here:
PHP get the item in an array that has the most duplicates
(2 answers)
Closed 1 year ago.
I have an array of numbers like this:
$array = array(1,1,1,4,3,1);
How do I get the count of most repeated value?
This should work:
$count=array_count_values($array);//Counts the values in the array, returns associatve array
arsort($count);//Sort it from highest to lowest
$keys=array_keys($count);//Split the array so we can find the most occuring key
echo "The most occuring value is $keys[0][1] with $keys[0][0] occurences."
I think array_count_values function can be useful to you. Look at this manual for details : http://php.net/manual/en/function.array-count-values.php
You can count the number of occurrences of values in an array with array_count_values:
$counts = array_count_values($array);
Then just do a reverse sort on the counts:
arsort($counts);
Then check the top value to get your mode.
$mode = key($counts);
If your array contains strings or integers only you can use array_count_values and arsort:
$array = array(1, 1, 1, 4, 3, 1);
$counts = array_count_values($array);
arsort($counts);
That would leave the most used element as the first one of $counts. You can get the count amount and value afterwards.
It is important to note that if there are several elements with the same amount of occurrences in the original array I can't say for sure which one you will get. Everything depends on the implementations of array_count_values and arsort. You will need to thoroughly test this to prevent bugs afterwards if you need any particular one, don't make any assumptions.
If you need any particular one, you'd may be better off not using arsort and write the reduction loop yourself.
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values, with some useless defaults */
$max = 0;
$max_item = $array[0];
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_item = $value;
}
}
After the foreach loop, $max_item contains the last item that appears the most in the original array as long as array_count_values returns the elements in the order they are found (which appears to be the case based on the example of the documentation). You can get the first item to appear the most in your original array by using a non-strict comparison ($amount >= $max instead of $amount > $max).
You could even get all elements tied for the maximum amount of occurrences this way:
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values */
$max = 0;
$max_items = array();
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_items = array($value);
} elif ($amount = $max) {
$max_items[] = $value;
}
}
$vals = array_count_values($arr);
asort($vals);
//you may need this end($vals);
echo key($vals);
I cant remember if asort sorts asc or desc by default, you can see the comment in the code.
<?php
$arrrand = '$arr = array(';
for ($i = 0; $i < 100000; $i++)
{
$arrrand .= rand(0, 1000) . ',';
}
$arrrand = substr($arrrand, 0, -1);
$arrrand .= ');';
eval($arrrand);
$start1 = microtime();
$count = array_count_values($arr);
$end1 = microtime();
echo $end1 - $start1;
echo '<br>';
$start2 = microtime();
$tmparr = array();
foreach ($arr as $key => $value);
{
if (isset($tmparr[$value]))
{
$tmparr[$value]++;
} else
{
$tmparr[$value] = 1;
}
}
$end2 = microtime();
echo $end2 - $start2;
Here check both solutions:
1 by array_count_values()
and one by hand.
<?php
$input = array(1,2,2,2,8,9);
$output = array();
$maxElement = 0;
for($i=0;$i<count($input);$i++) {
$count = 0;
for ($j = 0; $j < count($input); $j++) {
if ($input[$i] == $input[$j]) {
$count++;
}
}
if($count>$maxElement){
$maxElement = $count;
$a = $input[$i];
}
}
echo $a.' -> '.$maxElement;
The output will be 2 -> 3
$arrays = array(1, 2, 2, 2, 3, 1); // sample array
$count=array_count_values($arrays); // getting repeated value with count
asort($count); // sorting array
$key=key($count);
echo $arrays[$key]; // get most repeated value from array
String S;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String: ");
S = in.nextLine();
int count =1;
int max = 1;
char maxChar=S.charAt(0);
for(int i=1; i <S.length(); i++)
{
count = S.charAt(i) == S.charAt(i - 1) ? (count + 1):1;
if(count > max)
{
max = count;
maxChar = S.charAt(i);
}
}
System.out.println("Longest run: "+max+", for the character "+maxChar);
here is the solution
class TestClass {
public $keyVal;
public $keyPlace = 0;
//put your code here
public function maxused_num($array) {
$temp = array();
$tempval = array();
$r = 0;
for ($i = 0; $i <= count($array) - 1; $i++) {
$r = 0;
for ($j = 0; $j <= count($array) - 1; $j++) {
if ($array[$i] == $array[$j]) {
$r = $r + 1;
}
}
$tempval[$i] = $r;
$temp[$i] = $array[$i];
}
//fetch max value
$max = 0;
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] > $max) {
$max = $tempval[$i];
}
}
//get value
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] == $max) {
$this->keyVal = $tempval[$i];
$this->keyPlace = $i;
break;
}
}
// 1.place holder on array $this->keyPlace;
// 2.number of reapeats $this->keyVal;
return $array[$this->keyPlace];
}
}
$catch = new TestClass();
$array = array(1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 1, 2, 3, 1, 1, 2, 5, 7, 1, 9, 0, 11, 22, 1, 1, 22, 22, 35, 66, 1, 1, 1);
echo $catch->maxused_num($array);

Categories