How to get the minimum value from array row - php

I trying to get the minimum values from the any column contains "xx" in the column name.
Below is my code:
<?php
$array = array(
array(
'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
foreach($array as $item)
{
$lowestKey = '';
foreach($item as $key => $value)
{
if(strpos($key, 'xx') === 0)
{
if($lowestKey == '')
{
$lowestKey = $key;
}
else
{
if($value < $item[$lowestKey])
{
$lowestKey = $key;
}
}
}
}
echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey] . "\n";
}
?>

You have a function already for it:
http://php.net/manual/en/function.min.php
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
echo min(0, 'hello'); // 0
echo min('hello', 0); // hello
echo min('hello', -1); // -1
Combine it with array_values if this fits better your needs.

function _getNumber($array) {
return $array['id'];
}
$numbers = array_map('_getNumber', $array);
OR
$numbers = array_map(function($array) {
return $array['id'];
}, $array);
echo $min = min($numbers);
echo $max = max($numbers);

function find_lowest($array){
$new_array = array();
foreach($array as $key => $val ){
if(is_array($val)){
$new_array[$key] = find_lowest($val);
}else{
$new_array[$key] = $val ;
}
}
return min($new_array);
}
$array = array( array( 'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
echo find_lowest($array);

Instead of looping again inside just use the min() function.
$lowest_keys = array();
foreach($array as $item)
{
unset( $item[ 'id' ] );
$lowest_keys[] = min( $item );
}

Iterate each row/subarray with a foreach() loop or array_walk().
Extract and display the id (first element) value with array_shift().
Call min() on the remaining values in the respective subarray to determine the lowest value.
No conditional expressions. No unnecessary variables. Clean, concise, and effective.
Code: (Demo)
$array = [
['id' => 1, '10xx' => 14, '11xx' => 32, '12xx' => 4],
['id' => 2, '10xx' => 13, '11xx' => 36, '12xx' => 41]
];
array_walk($array, function($row) {
echo array_shift($row) , " : " , min($row) , "\n";
});
Output:
1 : 4
2 : 13

$array = array(
array(
'id' => 14,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
$lowestKey = '';
foreach($array as $arra){
foreach ($arra as $key=>$value){
if ($key == 'id'){
if(($value < $lowestKey )||( $lowestKey== '')){
$lowestKey = $value;
}
}
}
}
echo $lowestKey;

Related

Grouping of same values in an array

I have this array with year as its key and count as its value,
$dateRange = array([
"1990" => 10,
"1991" => 12,
"1992" => 12,
"1993" => 12,
"1994" => 12,
"1995" => 12,
"1996" => 6
]);
and how can I make it look like this *(getting consecutive year/s with a count/value of 12 then count its total value)
$dateRange = ([
"1990" => 10,
"1991-1995" => 60,
"1996" => 6
]);
I came up with the following solutions, it's not efficient with large data but will work.
1991-1995 will be string though.
$dateRange = array([
1990 => 10,
1991 => 12,
1992 => 12,
1993 => 12,
1994 => 12,
1995 => 12,
1996 => 6
]);
dump($dateRange[0]);
$first = reset($dateRange[0]);
$last = end($dateRange[0]);
$newArr = array([]);
$sum = 0;
$firstRange = null;
$lastRange = null;
foreach($dateRange[0] as $key => $item){
if($item == $first){
$newArr[0][$key] = $item;
}
elseif($item == $last){
$newArr[0][$firstRange.'-'.$lastRange] = $sum;
$newArr[0][$key] = $item;
}
else{
if($firstRange == null){
$firstRange = $key;
}
$lastRange = $key;
$sum += $item;
}
}
dd($newArr[0]);
Loop through each individual dataset(subarray) and
Sort the keys numerically.
Compare every current key with previous key to check if they are consecutive.
If prev_key + 1 == curr_key, then they are consecutive, else they are not.
Check the same for their values' equality as well.
In either step 2 or 3, if any of the conditions don't match, add the current range and it's sum to the result and start a new range from this index. Likewise, collect all the results.
Snippet:
<?php
$res = [];
foreach($dateRange as $k => $v){
$temp = [];
$keys = array_keys($v);
sort($keys, SORT_NUMERIC);
$prev = 0;
$sum = 0;
for($i = 0; $i < count($keys); ++$i){
if($i > 0 && ($keys[ $i - 1 ] + 1 != $keys[ $i ] || $v[ $keys[ $i - 1 ] ] !== $v[ $keys[ $i ] ])){
if($prev == $i - 1) $temp[ $keys[ $prev ]] = $sum;
else $temp[ $keys[$prev] . "-" . $keys[$i - 1]] = $sum;
$sum = 0;
$prev = $i;
}
$sum += $v[$keys[ $i ]];
if($i === count($keys) - 1){
if($prev == $i) $temp[ $keys[ $prev ]] = $sum;
else $temp[ $keys[$prev] . "-" . $keys[ $i ]] = $sum;
}
}
$res[] = $temp;
}
print_r($res);
Online Demo
Here is a more Laravel friendly solution using Framework collection methods.
Using Collection is more readable and more understandable.
$dateRange = [
[
"1990" => 10,
"1991" => 12,
"1992" => 12,
"1993" => 12,
"1994" => 12,
"1995" => 12,
"1996" => 6,
],
];
collect($dateRange)->map(function ($range)
{
return collect($range)->groupBy(function ($item)
{
return $item;
}, true)->mapWithKeys(function (Collection $item)
{
$sorted = $item->sortKeys();
$keys = $sorted->keys();
$firstYear = $keys->first();
$lastYear = $keys->last();
$sum = $item->sum();
return [($firstYear != $lastYear ? $firstYear.'-'.$lastYear : $firstYear) => $sum];
});
})->dd();
Output:
array:1 [▼
0 => Illuminate\Support\Collection {#2259 ▶
#items: array:3 [▶
1990 => 10
"1991-1995" => 60
1996 => 6
]
#escapeWhenCastingToString: false
}
]
$dateRange = [
'1990' => 10,
'1991' => 12,
'1992' => 12,
'1993' => 12,
'1994' => 12,
'1995' => 12,
'1996' => 6
];
ksort($dateRange);
$previousValue = '';
$result = [];
array_walk(
$dateRange,
function (int $value, string $key) use (&$previousValue, &$result) {
if ($previousValue === $value) {
$lastKey = array_key_last($result);
$result[substr($lastKey, 0, 4) . '-' . $key] = $result[$lastKey] + $value;
unset($result[$lastKey]);
} else {
$result[$key] = $value;
}
$previousValue = $value;
},
[]
);
print_r($result);
You have an array of arrays here. You could just do $dateRange = [...]; but I'll assume this is what you intended.
$dateRange = array([
"1990" => 10,
"1991" => 12,
"1992" => 12,
"1993" => 12,
"1994" => 12,
"1995" => 12,
"1996" => 6
]);
Using Collection methods, it should be easy.
$collection = collect($dateRange[0]);
$keys = $collection->keys();
$newKeys = [
$keys->shift(), // remove and return first key of $keys (1990)
$keys->pop(), // remove and return last key of $keys (1996)
"{$keys->first()}-{$keys->last()}", // concat first key and last key of $keys ("1991-1995")
];
// $newKeys is now equal to [1990, "1991-1995", 1996]
$newValues = [
0 => $collection->pull($newKeys[0]), // remove and return element 1990 from collection (10)
2 => $collection->pull($newKeys[1]), // remove and return element 1996 from collection (6)
1 => $collection->sum(), // return sum of remaining elements in collection (60)
];
ksort($newValues); // sort $newValues by its key (this is why I specified them in the order 0, 2, 1).
// $newValues is equal to [10, 60, 6]
$newArray = array_combine($newKeys, $newValues); // create a new array from $newKeys and $newValues

How to check the key of next index of arrays in PHP?

I have an PHP array :
$datas = array(
"abcd" => array(
"1639340364" => 1,
"1639362752" => 85,
"1639363500" => 74,
),
"efgh" => array(
"1639340364" => 78,
"1639362754" => 98,
"1639363500" => 46,
),
"ijkl" => array(
"1639340364" => 78,
"1639362754" => 98,
"1639363505" => 46,
),
);
I want to check the keys of each array and if not match need to add it on every array.
Expecting output like:
$datas = array(
"abcd" => array(
"1639340364" => 1,
"1639362752" => 85,
"1639362754" => 0,
"1639363500" => 74,
"1639363505" => 0,
),
"efgh" => array(
"1639340364" => 78,
"1639362752" => 0,
"1639362754" => 98,
"1639363500" => 46,
"1639363505" => 0,
),
"ijkl" => array(
"1639340364" => 78,
"1639362752" => 0,
"1639362754" => 98,
"1639363500" => 0,
"1639363505" => 46,
),
);
If the key is not exist need to add the key with value zero. Is that possible?
I tried with array_key_exists() function...
But I'm not sure where I want to check, when I'm checking It's return true(1). I know it's checking on the same array, Actually I want to know where I will check the condition?
foreach($datas as $key => $data ){
print_r($data);
foreach($data as $key => $point ){
$val = array_key_exists($key,$data);
echo $val;
}
}
I came up with this:
// prepare default keys
$keys = [];
foreach ($datas as $data) {
$keys = array_merge($keys, array_keys($data));
}
$keys = array_unique($keys);
sort($keys);
// construct default array with zeros
$default = array_combine($keys, array_fill(0, count($keys), 0));
// insert the default array
foreach ($datas as $key => $data) {
$datas[$key] = array_replace($default, $data);
}
// show result
echo '<pre>';
print_r($datas);
echo '</pre>';
I needed used a plethora of array functions. The idea is this: First I gather all the possible 'keys' from the array, make them unique, sort them and combine them into a new 'default' array containing only zero values. After that I use the array_replace() function to insert this array into the existing $datas array. This function does exactly what you want:
array_replace() replaces the values of array with values having the
same keys in each of the following arrays. If a key from the first
array exists in the second array, its value will be replaced by the
value from the second array.
It's not pretty or optimised, but here you go:
$subkeys = array();
foreach ($datas as $k => $d) {
foreach($d as $k2 => $d2) {
$subkeys[$k2] = 0;
}
}
foreach ($datas as $k => &$d) {
foreach ($subkeys as $xk => $xd) {
if ( ! array_key_exists($xk, $d)) {
$d[$xk] = $xd;
}
}
}

output of php array in a particular format

am trying to get output of following array in one format. its not getting
<?php
$distance_covered = array( '1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
The above is my array
i want output in the following format
Output: Array ( [DRIVER_1] => 51, [DRIVER_2] => 33, [DRIVER_3] => 24, [DRIVER_4] => 67, [DRIVER_5] => 34 )
this is the sum of distance travelled by each driver in all trips
i tried code like this,anybody knows please help
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
(!isset($res[$key])) ?
$res[$key] = $number :
$res[$key] += $number;
}
}
print_r($res);
?>
This one works for me
$res = array();
foreach($distance_covered as $value)//the array which you have given us
{
foreach($value as $key => $number) //loop over array of date
{
if(!isset($res[$key]))//check if the key exist in over defined array if no then run this
{
$res[$key] = array_sum($number);// Sum all distances of that driver
continue;//set the key and continue the foreach...
}
$res[$key] += array_sum($number);// Sum all distances of that driver
}
}
print_r($res);
die;
And the Output is
Array
(
[DRIVER_1] => 51
[DRIVER_2] => 33
[DRIVER_3] => 24
[DRIVER_4] => 67
[DRIVER_5] => 34
)
This should work:
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
foreach ($number as $n) {
if (isset($res[$key])) {
$res[$key] += $n;
} else {
$res[$key] = $n;
}
}
}
}
print_r($res);
Just traverse through array of arrays.
$distance_covered = array(
'1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
// Counting.
$merged = [];
foreach ($distance_covered as $day => $stats) {
foreach ($stats as $driver => $distances) {
if (!isset($merged[$driver])) {
$merged[$driver] = 0;
}
$merged[$driver] += array_sum($distances);
}
}
// Display.
echo "<pre>";
print_r($merged);
echo "</pre>";
You are close, but...
$res = array ();
foreach ( $distance_covered as $value ) {
foreach ( $value as $key=> $driver ) {
if ( isset($res[$key]) == false ){
$res[$key]=0;
}
$res[$key] += array_sum($driver);
}
}
print_r($res);
The first foreach simply splits the data down to the days.
The second one returns elements like $key = 'DRIVER_1' and $driver = array(3, 9).
If this is the first time you've encountered this driver, then you need to ensure that the element in $res exists, so set it to 0.
Once you know there is an element there, you can add in the sum of the values ( 3 & 9 in this case ) using the += array_sum($driver) bit. The += is simply adding to rather than having to say a=a+b, you can say a+=b.
[sarcastic voice] I can't believe everybody overlooked this convoluted function-based one-liner...
Code: (Demo)
var_export(array_map('array_sum', array_merge_recursive(...array_values($distance_covered))));
Output:
array (
'DRIVER_1' => 51,
'DRIVER_2' => 33,
'DRIVER_3' => 24,
'DRIVER_4' => 67,
'DRIVER_5' => 34,
)
*this is virtually guaranteed to process slower than any other posted answer.
Remove the first level associative keys (date strings) with array_values()
Unpack the array of arrays with the "splat operator" (...) and feed to array_merge_recursive() to group values
Sum the subarray values by calling array_sum() on each subarray with array_map()
(This is merely an exercise of thinking outside the box.)
Beyond that no one suggested using a null coalescing operator, so I'll post what that can look like:
$driver_totals = [];
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] = ($driver_totals[$driver] ?? 0) + array_sum($distances);
}
}
var_export($driver_totals);
And if you have a special scenario where you only need to know the distance for a single specific driver, you can call upon array_column() like this:
$target_driver = 'DRIVER_4';
$total_distance = 0;
foreach (array_column($distance_covered, $target_driver) as $distances) {
$total_distance += array_sum($distances);
}
echo "{$target_driver} drove for a distance of {$total_distance}";
*Notice that the order of the drivers within each date array is inconsequential because array_column() is smart enough to find the desired distance subarray.
Finally, if you declare a whitelist array of all possible drivers, you can:
control the order of the drivers in the output
avoid the iterated isset() conditions
ensure that drivers without any distance records are included in the output
Code:
$roster = ['DRIVER_6', 'DRIVER_5', 'DRIVER_4', 'DRIVER_3', 'DRIVER_2', 'DRIVER_1'];
$driver_totals = array_fill_keys($roster, 0);
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] += array_sum($distances);
}
}
var_export($driver_totals);

PHP re-order values

I have an array like the following:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1005, "id_user" => 5));
So it means 5 => 1004, 1005 and 4 => 1000, 1001, 1003 and 3 => 1002.
First, how do I get this structure? (possible with commas)
My algorithm for this solution would be something like (here's what I'm asking you guys..how to accomplish this):
$arr = array();
for($i = 0; $i <= count($content) - 1; $i++){
if exists key ($content[$i]['id_user']) IN $arr then
$arr = add_to_existing_key "," . $content[$i]['id_post']
} other wise {
$arr = add_new_key PLUS value $content[$i]['id_user'] <=> $content[$i]['id_post']
}
}
I need the commas so I could parse the info later.
Basically, the objective of this is to do a loop with $arr variable. Imagining that the array would have, finally, something like:
("id_user" => 5, "ids" => '1004,1005'),
("id_user" => 4, "ids" => '1000,1001,1003'),
("id_user" => 3, "ids" => '1002')
for($i = 0; $i <= count($arr) - 1; $i++){
$ids = explode(",", $arr[$i]['ids']);
$info = array();
for($y = 0; $y <= count($ids) - 1; $y++){
$query->("SELECT * FROM table WHERE id = $ids[$y]");
$info[] = array($name, $description);
}
$email->sendEmail($info); // id = 5 => info OF 1004, 1005
$info = array(); // clear array
// loop
// id = 4 => info OF 1000, 1001, 1003
// loop etc
}
Try this:
$arr = array();
// Loop through each content
foreach ($content as $post)
{
$arr[$post['id_user']][] = $post['id_post'];
}
This way, the result would be
$arr = array(
'5'=> array('1004', '1005'),
'4'=> array('1000', '1001', '1003'),
'3'=> array('1002')
);
Then you won't need to use "explode" just to split those comma-separated IDs
Also
I think you might be better off sticking with arrays instead of joining on commas and then exploding later:
foreach($content as $values) {
if(!isset($result[$values['id_user']])) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
print_r($result);
May be this variant will be exactly what you need:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1005, "id_user" => 5));
// Make preparation array
foreach ( $content as $values ) {
if ( !isset($result[$values['id_user']]) ) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
// Sort inner arrays
foreach ( $result as $key => $valueArray ) {
asort($result[$key]);
}
// Implode arrays to strings
array_walk($result, function(&$array, $key) {
$array = implode(',', $array);
});
// Final array
$result1 = array();
foreach ( $result as $userID => $idsString ) {
$result1[] = array("id_user" => $userID, "id_post" => $idsString);
}
print_r($result1);

Get min and max value in PHP Array

I have an array like this:
array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
)
I need to extract minimal and maximal Weight values.
In this example
$min_value = 175
$max_value = 200
Any help on how to do this ?
Thank you !
Option 1. First you map the array to get those numbers (and not the full details):
$numbers = array_column($array, 'weight')
Then you get the min and max:
$min = min($numbers);
$max = max($numbers);
Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:
$numbers = array_map(function($details) {
return $details['Weight'];
}, $array);
Option 3.
Option 4. If you only need a min OR max, array_reduce() might be faster:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['weight']);
}, PHP_INT_MAX);
This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.
foreach ($array as $k => $v) {
$tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
$highest_weight = max(array_column($details, 'Weight'));
How to get the min value
$lowest_weight = min(array_column($details, 'Weight'));
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
How about without using predefined functions like min or max ?
//find max
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val < $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
//find min
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val > $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
$num = array (0 => array ('id' => '20110209172713', 'Date' => '2011-02-09', 'Weight' => '200'),
1 => array ('id' => '20110209172747', 'Date' => '2011-02-09', 'Weight' => '180'),
2 => array ('id' => '20110209172827', 'Date' => '2011-02-09', 'Weight' => '175'),
3 => array ('id' => '20110211204433', 'Date' => '2011-02-11', 'Weight' => '195'));
foreach($num as $key => $val)
{
$weight[] = $val['Weight'];
}
echo max($weight);
echo min($weight);
<?php
$array = array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
);
foreach ($array as $key => $value) {
$result[$key] = $value['Weight'];
}
$min = min($result);
$max = max($result);
echo " The array in Minnumum number :".$min."<br/>";
echo " The array in Maximum number :".$max."<br/>";
?>
$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);
asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
print_r($count);
$maxsize = 0;
$maxvalue = 0;
foreach($count as $a=>$y){
echo "<br/>".$a."=".$y;
if($y>=$maxvalue){
$maxvalue = $y;
if($a>$maxsize){
$maxsize = $a;
}
}
}
echo "<br/>max = ".$maxsize;
print fast five maximum and minimum number from array without use of sorting array in php
:-
<?php
$array = explode(',',"78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73");
$t=0;
$l=count($array);
foreach($array as $v)
{
$t += $v;
}
$avg= $t/$l;
echo "average Temperature is : ".$avg." ";
echo "<br>List of seven highest temperatsures :-";
$m[0]= max($array);
for($i=1; $i <7 ; $i++)
{
$m[$i]=max(array_diff($array,$m));
}
foreach ($m as $key => $value) {
echo " ".$value;
}
echo "<br> List of seven lowest temperatures : ";
$mi[0]= min($array);
for($i=1; $i <7 ; $i++)
{
$mi[$i]=min(array_diff($array,$mi));
}
foreach ($mi as $key => $value) {
echo " ".$value;
}
?>

Categories