How to get array min value - php

I have multidimensional array and me need to get a minimum value.
Array may be [65,4,4,511,5,[[54,54[.[.[..].].]] and so on.
example code
<?php
$arr = [5, 1 , 2, 3, [1,5,59,47,58,[0,12,562]]];
function NumMin($arr)
{
$num = '';
foreach ($arr as $item => $i) {
if(is_array($i)){
NumMin($i);
}
else{
$num .= $i.',';
}
}
$num .= $num;
return $num;
}
$g = NumMin($arr);
var_dump($g);
I need to get 0

You can use array_walk_recursive() function to flatten a given array (makes it one-dimensional).
And use simply min() function for getting the desired output after.
array_walk_recursive($arr, function($v) use (&$res){
$res[]=$v;
});
echo min($res);
Demo

<?php
$GLOBALS["min"] = 999999; //min value int
$arr = [[[5,6],7],9,7,5, 1 , 2, 3, [1,5,59,47,58,[1,12,562]]];
array_walk_recursive($arr, 'NumMin');
function NumMin($item)
{
if(intval($item) <= intval($GLOBALS["min"]))
{
$GLOBALS["min"] = intval($item);
}
}
// The end, $GLOBALS["min"] will have the least value
echo $GLOBALS["min"];
?>

Related

Get a total from symmetric intigers from array in php?

ok so i have array for example $arr= "/43sdsd555ksldk66sd"544fdfd";
I take numbers using preg_match_all '/\d+/', and array_map('intval', $zni[0]);
Now the problem is i need to reverse those whole int to see if they are symmetric,like 555 and 66 , and if they are GET A TOTAL OF THEM.(total of only symmetric numbers)
i tried to use function " strrev "and got symmetric numbers, but i don't know how to put them in a one place IF THEY ARE symmetric and calculate them.
<?php
$numbers = "";
if (isset($_GET['submit']))
{
$numbers = ($_GET['niz']);
preg_match_all('/\d+/', $numbers, $zni);
$numtwo= array_map('intval', $zni[0]);
}
foreach ($numtwo as $num)
{
$reverse = strrev($num);
var_dump($reverse);
if ($num == $reverse)
{
$reverse = "true";
} else {
$reverse = "false";
}
var_dump($reverse);
}
Since you already got most of the way there and all you were missing basically was to use + or +=, here is an easy example on how to do it:
$input = "/43sdsd555ksldk66sd544fdfd";
$total = 0;
preg_match_all('/\d+/', $input, $m);
foreach ($m[0] as $d)
if ($d == strrev($d))
$total += $d;
var_dump($total); // => int(621)
Using intval() is not necessary as PHP will implicitly cast between types as needed.
Alternatively you can replace the loop with PHP's array_* functions:
$input = "/43sdsd555ksldk66sd544fdfd";
preg_match_all('/\d+/', $input, $m);
$total = array_sum(array_filter($m[0], function ($v) { return $v == strrev($v); }));
var_dump($total); // => int(621)
Here we use an anonymous function with array_filter() to generate a new array that only contains palindrome numbers from the original matches which is then given to array_sum().
So all that's needed to transform your original code into a working example, is introducing a variable and summing up:
<?php
$numbers = "";
if (isset($_GET['submit']))
{
$numbers = ($_GET['niz']);
preg_match_all('/\d+/', $numbers, $zni);
$numtwo= array_map('intval', $zni[0]);
}
$total = 0; // new variable
foreach ($numtwo as $num)
{
$reverse = strrev($num);
var_dump($reverse);
if ($num == $reverse)
{
$reverse = "true";
$total += $num; // sum up
} else {
$reverse = "false";
}
var_dump($reverse);
}
var_dump($total); // => int(621)

PHP Reverse Selection Sort

I would like to perform a selection sort of an array, using PHP. But instead of having it move from left to right, I would like it to move from right to left.
Example of Logic
$array = array(3, 0, 2, 5, -1, 4, 1);
function swap($data1, $a, $b) {
//Create temp storage for b
$bTmp = $data1[$b];
//Switch b for a value
$data1[$b] = $data1[$a];
//Set a as b value before switch
$data1[$a] = $bTmp;
//Return the sorted data
return $data1;
}
function selection($data)
{
$i1=count($data)-1;
$j1=$i1-1;
//For each value in the array
for($i=$i1; $i>1; $i--) {
//Set the minimum as the current position
$min = $i;
//Check the next value in the array (left)
for($j=$j1; $j>0; $j--) {
//If the original value (i) is bigger than the next value...
if ($data[$j]>$data[$min]) {
//Set the smaller value to be the next value
$min = $j;
}
}
$data = swap($data, $i, $min);
}
return $data;
}
//Perform the module using the array values and then output values with keys
echo(var_dump(selection($array)));
I have tried to incorporate this by using a decrementing for loop. But it only appears to partially sort the array.
Check this, it will work as expected
<?php
$array = array(3, 0, 2, 5, -1, 4, 1);
// $array = array(24,12,16,32,41,22);
function swap($data1, $a, $b) {
$bTmp = $data1[$b];
$data1[$b] = $data1[$a];
$data1[$a] = $bTmp;
return $data1;
}
function selection($data)
{
$i1=count($data)-1;
$j1 = $i1;
foreach($data as $key => $val){
for($i=$i1; $i>0; $i--) {
$min = $i;
$j1 = $min;
for($j=$j1; $j>=0; $j--) {
if ($data[$j]>$data[$min]) {
$data = swap($data, $j, $min);
$min = $j;
}
}
}
}
return $data;
}
echo(var_dump(selection($array)));
?>

how to get top 3 values in php array and their index

I want to get the highest value, the second highest value and the third highest value
For example, I have an array like:
$n = array(100,90,150,200,199,155,15,186);
I know the method to get the max value and its index:
echo max($n); //200
$maxs = array_keys($n, max($n));
echo $maxs[0]; //3
I want to get the top 3 values and their index like : value: 200, 199, 186 index:3,4,7
How can i get them?
Try this:
$n = array(100,90,150,200,199,155,15,186);
rsort($n);
$top3 = array_slice($n, 0, 3);
echo 'Values: ';
foreach ($top3 as $key => $val) {
echo "$val\n";
}
echo '<br>';
echo 'Keys: ';
foreach ($top3 as $key => $val) {
echo "$key\n";
}
Output:
Values: 200 199 186
Keys: 0 1 2
This should do the trick:
function maxNitems($array, $n = 3){
asort($array);
return array_slice(array_reverse($array, true),0,$n, true);
}
Use like:
maxNitems(array(100,90,150,200,199,155,15,186));
You can achieve it by using arsort() and array_keys() functions:
arsort() sorts an array in reverse order and maintains index association
array_keys() returns all the keys or a subset of the keys of an array
Process array:
$n = array(100,90,150,200,199,155,15,186);
arsort($n);
$keys = array_keys($n);
Get top 3 values:
echo $n[$keys[0]];
echo $n[$keys[1]];
echo $n[$keys[2]];
$n = array(100,90,150,200,199,155,15,186);
arsort($n);
$x = 0;
while (++$x <= 3)
{
$key = key($n);
$value = current($n);
next($n);
echo "Key : " . $key . " Value : " . $value . '<br>' ;
}
Easier I would think:
arsort($n);
$three = array_chunk($n, 3, true)[0];
//or
$three = array_slice($n, 0, 3, true);
try this:
public function getTopSortedThree(array $data, $asc = true)
{
if ($asc) {
uasort($data, function ($a, $b) { return $a>$b;});
} else {
uasort($data, function ($a, $b) { return $a<$b;});
}
$count = 0;
$result = [];
foreach ($data as $key => $value) {
$result[] = $data[$key];
$count++;
if ($count >= 3){
break;
}
}
return $result;
}
send false for desc order and nothing for asc order
This functionality doesn't losing keys.

php find number range of array

i have an array like this:
$d=array('good'=>10,'very good'=>20,'bad'=>1);
i want to find key from it when 13 number closest vlaue of array.
for example 16 close to 20 in $d array .
like result:
key:very good
value:20
Code
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
foreach(array_chunk($find, 5) as $val) {
echo reset($val) . "-" . end($val);
}
sorry for my english.
This is not very pretty code, but I think it does what you want it to.
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$closest = array('int' => -1, 'key' => null);
$find = 16;
foreach($d as $k=>$v) {
if ($closest['int'] == -1) { $closest['int'] = abs($find-$v); $closest['key'] = $k; continue; }
if (abs($find - $v) < $closest['int']) {
$closest['int'] = abs($find-$v);
$closest['key'] = $k;
}
}
echo "key:".$closest['key']."
value:".$d[$closest['key']];
You can try
$d = array('good' => 10,'very good' => 20,'bad' => 1);
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,13));
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,16));
Output
Find:13, Closest: 10, Grade: good
Find:16, Closest: 20, Grade: very good
Function Used
function findClosest($array, $find) {
$map = array_map(function ($v) use($find) {
return abs($v - $find);
}, $array);
asort($map);
return array($find,$array[key($map)],key($map));
}
try code
$d = array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
$result = get_closest($d , $find);
echo $result;
function get_closest($array = array(), $key){
$new_arr = array();
foreach($array AS $index=>$arr){
if($key < $arr) {
$new_arr[$index] = $arr - $key;
}
else{
$new_arr[$index] = $key - $arr;
}
}
$min_val = min($new_arr);
$res = array_search( $min_val , $new_arr);
return $res;
}
thanks
you can use array_values function to get all values as $a, then you can sort $a.After sort you can find two numbers between $find, then you can compare those two numbers.

PHP create array where key and value is same

I am using the range() function to create an array. However, I want the keys to be the same as the value. This is ok when i do range(0, 10) as the index starts from 0, however if i do range(1, 11), the index will still start from 0, so it ends up 0=>1 when i want it to be 1=>1
How can I use range() to create an array where the key is the same as the value?
How about array_combine?
$b = array_combine(range(1,10), range(1,10));
Or you did it this way:
$b = array_slice(range(0,10), 1, NULL, TRUE);
Find the output here: http://codepad.org/gx9QH7ES
There is no out of the box solution for this. You will have to create the array yourself, like so:
$temp = array();
foreach(range(1, 11) as $n) {
$temp[$n] = $n;
}
But, more importantly, why do you need this? You can just use the value itself?
<?php
function createArray($start, $end){
$arr = array();
foreach(range($start, $end) as $number){
$arr[$number] = $number;
}
return $arr;
}
print_r(createArray(1, 10));
?>
See output here: http://codepad.org/Z4lFSyMy
<?php
$array = array();
foreach (range(1,11) as $r)
$array[$r] = $r;
print_r($array);
?>
Create a function to make this:
if (! function_exists('sequence_equal'))
{
function sequence_equal($low, $hight, $step = 1)
{
return array_combine($range = range($low, $hight, $step), $range);
}
}
Using:
print_r(sequence_equal(1, 10, 2));
Output:
array (
1 => 1,
3 => 3,
5 => 5,
7 => 7,
9 => 9,
)
In PHP 5.5 >= you can use Generator to make this:
function sequence_equal($low, $hight, $step = 1)
{
for ($i = $low; $i < $hight; $i += $step) {
yield $i => $i;
}
}

Categories