php find number range of array - php

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.

Related

why mycode after for loop is not executed? [duplicate]

This question already has answers here:
Code after a return statement in a PHP function
(3 answers)
Closed 6 months ago.
please check my code. i have some program to return the third largest word in a given array.
if in the third largest word has a same letters long, so retrun the last one.
for example ['world', 'hello', 'before', 'all', 'dr'] the output should be 'hello'.
my program is working fine, however when I want to echo the $result, the code doesn't execute.
here is my code:
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "THIS RESULT SHOULD BE RE ASSIGNED, BUT WHY !!!!!";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
return $result;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
return $result;
}
}
echo "THIS LINE IS NOT WORKING";
echo $result;
You have to use break instead of return.
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
break;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
break;
}
}
echo $result;
Simply remove the return statements in the loop. instead of return, perhaps use break.
You can try this way as well.
<?php
/**
* Read more about here
* https://www.php.net/manual/en/function.usort.php
*/
function sort_by_length($a,$b){
return strlen($b)-strlen($a);
}
$array =['world', 'hello', 'before', 'all', 'dr'];
usort($array,'sort_by_length'); // sorting array with a custom function.
if(count($array) >= 2) {
$sliced = array_slice($array, 2);
$result = $sliced[0];
/**
* Read more at
* 1. https://www.php.net/manual/en/function.next.php
* 2. https://www.php.net/manual/en/function.current.php
*/
while(strlen(current($sliced)) == strlen(next($sliced))){
$result = current($sliced);
}
echo $result;
} else {
echo "Not enough items in array.";
}
This will output
hello
Remove the return .It return the value so any code after it will not be executed.

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

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.

permutation/generate combination prefix and suffix

I have an array of prefixes, an array of base words and an array of suffixes. I would like to see every combination that can be made.
Example:
prefixes: 1 2
words: hello test
suffixes: _x _y
Results:
1hello_x
1hello_y
1hello
1test_x
1test_y
1test
1_x
1_y
1
2hello_x
2hello_y
2hello
2test_x
2test_y
2test
2_x
2_y
2
hello_x
hello_y
hello
test_x
test_y
test
_x
_y
y
How can I do this?
Edit: Thanks for all the responses, I am going through the solutions but it seems like if there are no prefixes, then it will fail for combination. It should still go through the base words and suffixes, even without any prefixes.
function combineAll ($prefixes, $words, $suffixes)
{
$combinations = array ();
foreach ($prefixes as $prefix)
{
foreach ($words as $word)
{
foreach ($suffixes as $suffix)
{
$combinations[] = $prefix.$word.$suffix;
}
}
}
return $combinations;
}
for each $prefix in $prefixes {
for each $base in $basewords {
for each $suffix in $suffixes {
echo $prefix.$base.$suffix."\n"
}}}
This will do what you want, I believe there is no builtin function to do this in php (Though there is in python)
this should get you started:
http://ask.amoeba.co.in/php-combinations-of-array-elements/
//$a = array("1", "2");
$b = array("hello", "test");
$c = array("_x", "_y");
if(is_array($a)){
$aG = array($a,$b, $c);
}else{
$aG = array($b, $c);
}
$codes = array();
$pos = 0;
generateCodes($aG);
function generateCodes($arr) {
global $codes, $pos;
if(count($arr)) {
for($i=0; $i<count($arr[0]); $i++) {
$tmp = $arr;
$codes[$pos] = $arr[0][$i];
$tarr = array_shift($tmp);
$pos++;
generateCodes($tmp);
}
} else {
echo join("", $codes)."<br/>";
}
$pos--;
}
result:
1hello_x1hello_y1test_x1test_y2hello_x2hello_y2test_x2test_y

how to write function Max($array) which returns the maximum value contained in $array or some array nested within $array

Eg:
$array= array(array(141,151,161),2,3,array(101,202,array(303,606)));
output :606
What you need is to recursively go through your array ; which means the max function, which is not recursive, will not be "enough".
But, if you take a look at the users's notes on the manual page of max, you'll find this note from tim, who proposes this recursive function (quoting) :
function multimax( $array ) {
// use foreach to iterate over our input array.
foreach( $array as $value ) {
// check if $value is an array...
if( is_array($value) ) {
// ... $value is an array so recursively pass it into multimax() to
// determine it's highest value.
$subvalue = multimax($value);
// if the returned $subvalue is greater than our current highest value,
// set it as our $return value.
if( $subvalue > $return ) {
$return = $subvalue;
}
} elseif($value > $return) {
// ... $value is not an array so set the return variable if it's greater
// than our highest value so far.
$return = $value;
}
}
// return (what should be) the highest value from any dimension.
return $return;
}
Using it on your array :
$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
$max = multimax($arr);
var_dump($max);
Gives :
int 404
Of course, this will require a bit more testing -- but it should at least be a start.
(Going through the users' notes on manual pages is always a good idea : if you're having a problem, chances are someone else has already had that problem ;-) )
Same idea as Pascal's solution, only shorter thanks to the Standard PHP Library
$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
echo rmax($arr);
function rmax(array $arr) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
// initialize $max
$it->next(); $max = $it->current();
// "iterate" over all values
foreach($it as $v) {
if ( $v > $max ) {
$max = $v;
}
}
return $max;
}
http://www.java2s.com/Code/Php/Data-Structure/FindtheMaximumValueinaMultidimensionalArray.htm
function recursive_array_max($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = recursive_array_max($value);
}
if (!(isset($max))) {
$max = $value;
} else {
$max = $value > $max ? $value : $max;
}
}
return $max;
}
$dimensional = array(
7,
array(3, 5),
array(5, 4, 7, array(3, 4, 6), 6),
14,
2,
array(5, 4, 3)
);
$max = recursive_array_max($dimensional);
$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404)));
$callback = function ($value, $key) use (&$maximo) {
if( $value > $maximo){
$maximo = $value;
}
};
array_walk_recursive($arr, $callback);
echo '<pre>'; print_r($maximo);``
A more elegant solution:
function MaxArray($arr)
{
function findMax($currentValue, $currentKey)
{
global $maxValue;
$maxValue = ($currentValue > $maxValue ? $currentValue : $maxValue);
}
array_walk_recursive($arr, 'findMax');
return $GLOBALS['maxValue'];
}
It's very simple
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$max = max(iterator_to_array($iterator, false));
Finding the max avoiding too much recursion :
function array_max(array $array) {
$context = func_get_args();
$max = -INF;
while (!empty($context)) {
$array = array_pop($context);
while (!empty($array)) {
$value = array_pop($array);
if (is_array($value)) {
array_push($context, $value);
}
elseif ($max < $value) {
$max = $value;
}
}
}
return $max;
}
A more general method avoiding too much recursion :
function array_reduce_recursive($default, array $array, $callback = null) {
$context = func_get_args();
$count = func_num_args();
if (is_callable(func_get_arg($count - 1))) {
$callback = array_pop($context);
}
else {
$callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
}
$reduced = array_shift($context);
while (!empty($context)) {
$array = array_pop($context);
while (!empty($array)) {
$value = array_pop($array);
if (is_array($value)) {
array_push($context, $value);
}
else {
$reduced = $callback($reduced, $value);
}
}
}
return $reduced;
}
function array_max_recursive() {
$args = func_get_args();
$callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
return array_reduce_recursive(-INF, $args, $callback);
}
By this way you can specify the callback method if you are looking for something else than the biggest number. Also this method takes several arrays.
The end way is less efficient of course.
With this you have a full compatibility with lot of PHP version.
function MaxArray($arr) {
$maximum = 0;
foreach ($arr as $value) {
if (is_array($value)) {
//print_r($value);
$tmaximum = MaxArray($value);
if($tmaximum > $maximum){
$maximum = $tmaximum;
}
}
else
{
//echo $value.'\n';
if($value > $maximum){
$maximum = $value;
}
}
}
return $maximum;
}

Categories