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
https://forums.phpfreaks.com/topic/261634-php-arrays/
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
https://forums.phpfreaks.com/topic/261634-php-arrays/#findComment-1340649
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
https://forums.phpfreaks.com/topic/261634-php-arrays/#findComment-1340666
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.