Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.