finding an array range in PHP - php

I have a range of values in an array like:
$values = array(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5);
I need to find the index of the smallest value in that array that's greater than or equal to a specified number. For example, if the user inputs 0.25, I need to know that the first array index is 2.
In other languages I've used, like R, there is a 'which' function that will return an array of indices that meet some criteria. I've not found that in PHP, so i'm hopeful someone else has solved this.
Thanks.

You can use array_filter
It does exactly what R which does.

Hope this function will help you,
function find_closest_item($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array); // or return NULL;
}

I don't know if there's a built in function for that, but this should work:
function getClosest($input, $array)
{
foreach($array as $value)
{
if ($value >= $input)
{
return $value;
}
}
return false;
}

You can use the following working logic. There might be other built in functions which can be used to solve this problem.
<?php
$values = array(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5);
$search=0.35;
$result_index = NULL;
$result_value=NULL;
$count=count($values);
for($i=0;$i<$count;$i++) {
if($values[$i]<$search) {
continue;
}
if($result_index==NULL) {
$result_index = $i;
$result_value = $values[$i];
continue;
}
if($values[$i]<$result_value) {
$result_index = $i;
$result_value = $values[$i];
}
}
print $result_index . " " . $result_value;
?>

You can build your own custom function:
function findIndex($input_array, $num)
{
foreach($input_array as $k => $v)
{
if($v >= $num)
{
return $k;
}
}
return false;
}
This function will return array index (key). If you don't want index, but the value, then other functions posted here will do the job. You should clarify what exactly you want to get as your question is a little bit amiguous

Related

PHP Function Array values not changing

Ive created a function that takes an array as a parameter and changes all values to 4, but it doesn't work and i don't understand why. Really bothering me, could use help thank you!
$cup3 = array (1,4,3,5,7,2);
roll($cup3);
print_r($cup3);
function roll($array)
{
foreach($array as &$value)
{
$value = 4;
}
return $array;
}
Output: (1,4,3,5,7,2) instead of all 4s
Either pass by reference &$array to edit $cup3 directly:
roll($cup3);
print_r($cup3);
function roll(&$array)
{
foreach($array as &$value)
{
$value = 4;
}
}
Or use the return from the function:
$cup3 = roll($cup3);
print_r($cup3);
function roll($array)
{
foreach($array as &$value)
{
$value = 4;
}
return $array;
}

How do I change the unknown array depth and change all of the letters from lower to upper in php array?·

$ar = array(10, 102, 199, "a"=>array('B','c','d'=>array('e','f')),'g','h');
I want to change all of the lower letters to upper (A B C D E F G H).
I tried this:
function toto($arr,$depth='1'){
$tem=array();
foreach ($arr as $key => $value) {
if(is_string($value)){
$tem[]=strtoupper($value);
}elseif(is_array($value)&&array_depth($value)>1){
// $J=str_repeat('[]', (array_depth($value)));
$tem[]=array_map('strtoupper',$value);
}else{
$tem[]=$value;
}
}
return $tem;
}
And I tried getting the array depth with this:
function array_depth($array) {
$max_depth = 1;
foreach ($array as $value) {
if (is_array($value)) {
$depth = array_depth($value) + 1;
if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}
return $max_depth;
}
How can I achieve these two things?
Perhaps a quick look at the PHP docs would have shown you the array_walk_recursive() function which would let you do:
array_walk_recursive(
$ar,
function (&$value, $key) {
$value = strtoupper($value);
}
);
for setting every string at every level of a multi-dimensional to uppercase.... and then you don't even need to know the array depth
You could use this one-liner:
$ar = json_decode(strtoupper(json_encode($ar)),true);
first it is encoded to json, then strtoupper called and decoded as array again.
This way you will get both keys and values uppercased.
using array_map() :-
function to_upper($n)
{
return(strtoupper($n));
}
$input = array('a','b','c');
$output = array_map("to_upper", $input);
print_r($output);

php foreach on array when arrays might be nested

The following code uses foreach on an array and if the value is an array it does a for each on the nested array
foreach ($playfull as $a)
{
if (is_array($a))
{
foreach ($a as $b)
{
print($b);
print("<p>");
}
} else {
print($a);
print("<p>");
}
}
This only works if you know that the arrays may only be nested one level deep
If arrays could be nested an unknown number of levels deep how do you achieve the same result? (The desired result being to print the value of every key in every array no matter how deeply nested they are)
You can use array_walk_recursive. Example:
array_walk_recursive($array, function (&$val)
{
print($val);
}
This function is a PHP built in function and it is short.
Use recursive functions (that are functions calling themselves):
function print_array_recursively($a)
{
foreach ($a as $el)
{
if (is_array($el))
{
print_array_recursively($el);
}
else
{
print($el);
}
}
}
This is the way, print_r could do it (see comments).
You want to use recursion, you want to call your printing function in itself, whenever you find an array, click here to see an example
$myArray = array(
"foo",
"bar",
"children" => array(
"biz",
"baz"),
"grandchildren" => array(
"bang" => array(
"pow",
"wow")));
function print_array($playfull)
{
foreach ($playfull as $a)
{
if (is_array($a))
{
print_array($a);
} else {
echo $a;
echo "<p>";
}
}
}
echo "Print Array\n";
print_array($myArray);
You could use a recursive function, but the max depth will be determined by the maximum nesting limit (see this SO question, Increasing nesting functions calls limit, for details about increasing that if you need it)
Here's an example:
$array = array(1,array(2,3,array(4,5)),6,7,8);
function printArray($item)
{
foreach ($item as $a)
{
if (is_array($a))
{
printArray($a);
} else {
print($a);
print("<p>");
}
}
}
printArray($array);
I hope that helps.
Try this -
function array_iterate($arr, $level=0, $maxLevel=0)
{
if (is_array($arr))
{
// unnecessary for this conditional to enclose
// the foreach loop
if ($maxLevel < ++$level)
{ $maxLevel = $level; }
foreach($arr AS $k => $v)
{
// for this to work, the result must be stored
// back into $maxLevel
// FOR TESTING ONLY:
echo("<br>|k=$k|v=$v|level=$level|maxLevel=$maxLevel|");
$maxLevel= array_iterate($v, $level, $maxLevel);
}
$level--;
}
// the conditional that was here caused all kinds
// of problems. so i got rid of it
return($maxLevel);
}
$array[] = 'hi';
$array[] = 'there';
$array[] = 'how';
$array['blobone'][] = 'how';
$array['blobone'][] = 'are';
$array['blobone'][] = 'you';
$array[] = 'this';
$array['this'][] = 'is';
$array['this']['is'][] = 'five';
$array['this']['is']['five'][] = 'levels';
$array['this']['is']['five']['levels'] = 'deep';
$array[] = 'the';
$array[] = 'here';
$var = array_iterate($array);
echo("<br><br><pre>$var");

How to know if an associative array has the same value for all the recurrence?

I have an associative array like this:
9584=>string
5324=>string
6543=>string
The key is always a number but I assign it dynamically so I don't know the numbers and probably they are not consecutive.
I need to know if the string is the same in ALL of the occurrence in the array.
If you can help me thank you... and sorry for my horrible English
Let me count the ways... There are bound to be more:
if(count(array_flip($array)) === 1) { }
if(count(array_unique($array)) === 1) { }
if(count(array_count_values($array)) === 1) { }
Read the first value and browse your array until you find a different one.
<?php
function allTheSame($array)
{
if (count($array) != 0)
{
$first = reset($array);
foreach($array => $v)
{
if ($v !== $first)
{
return false;
}
}
}
return true;
}

access php array children through parameters?

I have a unique case where I have an array like so:
$a = array('a' => array('b' => array('c' => 'woohoo!')));
I want to access values of the array in a manner like this:
some_function($a, array('a')) which would return the array for position a
some_function($a, array('a', 'b', 'c')) which would return the word 'woohoo'
So basically, it drills down in the array using the passed in variables in the second param and checks for the existence of that key in the result. Any ideas on some native php functions that can help do this? I'm assuming it'll need to make use of recursion. Any thoughts would be really appreciated.
Thanks.
This is untested but you shouldn't need recursion to handle this case:
function getValueByKey($array, $key) {
foreach ($key as $val) {
if (!empty($array[$val])) {
$array = $array[$val];
} else return false;
}
return $array;
}
You could try with RecursiveArrayIterator
Here is an example on how to use it.
Here’s a recursive implementation:
function some_function($array, $path) {
if (!count($path)) {
return;
}
$key = array_shift($path);
if (!array_key_exists($key, $array)) {
return;
}
if (count($path) > 1) {
return some_function($array[$key], $path);
} else {
return $array[$key];
}
}
And an iterative implementation:
function some_function($array, $path) {
if (!count($path)) {
return;
}
$tmp = &$array;
foreach ($path as $key) {
if (!array_key_exists($key, $tmp)) {
return;
}
$tmp = &$tmp[$key];
}
return $tmp;
}
These functions will return null if the path is not valid.
$a['a'] returns the array at position a.
$a['a']['b']['c'] returns woohoo.
Won't this do?

Categories