Jump to content

PHP arrays


gary00ie

Recommended Posts

Hi,

 

I need to do this:

Write a method to quickly find the array index position of a given number in a ascending sorted array of numbers. e.g. in an array { 1, 2, 5, 10, 102 }, the array index position of a given number 5, would have an answer of 2. We're looking for an answer that's better than O(n).

 

I was using php's built in methods but I need to do this with a basic function using no helper methods.

 

Can anybody help me out with this?

 

Thanks in advance.

Link to comment
Share on other sites

Can anybody help me out with this?

 

Seems pretty straight forward, where exactly are you stuck?

 

I was using php's built in methods but I need to do this with a basic function using no helper methods.

 

Sorry, but that statement makes little sense.

Link to comment
Share on other sites

Can anybody help me out with this?

 

Seems pretty straight forward, where exactly are you stuck?

 

I was using php's built in methods but I need to do this with a basic function using no helper methods.

 

Sorry, but that statement makes little sense.

 

I was using the built in arryay_keys and array_search to do this.  But, I need to do it without using those methods.

Link to comment
Share on other sites

Whatever. Here is an example without any error handling written for PHP5.4.

 

function findIndex($array, $value) {
  return array_reverse($array)[$value];
}

 

Should give you the idea without handing you the code.

Link to comment
Share on other sites

function findIndex($array, $value){
     if(count($array) > 0){
          $i = 0;
          foreach($array AS $val){
               // check if val is equal to value, if it is return $i
               // increment $i
          }
     }

     return -1;
}

 

Alternatively you could use a for loop

 

$count = count($array);
for($i = 0; $i < $count; $i++){
     // if array position at $i equals your value, return $i
}

 

-1 is used to indicate the value was never found. So when using the function

 

$index = findIndex($array, $value);
if($index < 0){
// not found
}else {
// found at $index
}

Link to comment
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.