Jump to content

Find Array Key


petenaylor

Recommended Posts

Hi all

 

I have a function below that searches an array and assigns it to $totalmonthlycost.

 

I need to know how I get the array key of the chosen array value ($m12 - $m60)

 

How do I return the array key in the below code?

 

$monthvalues = array($m12,$m18,$m24,$m30,$m36,$m42,$m48,$m54,$m60);
function closest($monthvalues, $number){
#does the array already contain the number?
if($i = array_search( $number, $monthvalues)) return $i;
#add the number to the array
$monthvalues[] = $number;
#sort and refind the number
sort($monthvalues);
$i = array_search($number, $monthvalues);
#check if there is a number above it
if($i && isset($monthvalues[$i-1])) return $monthvalues[$i-1];
//alternatively you could return the number itself here, or below it depending on your requirements
}
$totalmonthlycost = closest($monthvalues, $idealcostpermonth);

 

Thanks for your help.

 

Pete

Link to comment
https://forums.phpfreaks.com/topic/271537-find-array-key/
Share on other sites

you could try changing your returns to

return array($i, $monthvalues);

then just call the values from the function :

$values = closest($monthvalues, $number);
echo "{$values['1']} was found at position {$values['0']}";

or something along those lines should do it.

Link to comment
https://forums.phpfreaks.com/topic/271537-find-array-key/#findComment-1397209
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.