Jump to content

Find Array Key


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
$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.



Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

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

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.