0

I am currently dealing with some task, that requires to get keys of array at which element appears for the first and very last time.

Example:

$array = [1,2,3,2,4,1,1,2,3];

getFor(1); // keys 0 and 6
getFor(2); // keys 1 and 7
getFor(3); // keys 2 and 8

I would appreciate any help with this one.

P.S. Simple foreaching the array is not effective here, 'cause it takes too much time for very long arrays (over 1000000 entries). So I'm looking for not that obvious solution.

Also, getFor return type is not essential, it could be either a string or array of two values.

3
  • 4
    And where are you stuck at doing it? Commented Jul 8, 2016 at 11:51
  • Do you expect the code or you have done something? Commented Jul 8, 2016 at 11:53
  • 3
    have a look at stackoverflow.com/questions/21223286/… Commented Jul 8, 2016 at 11:53

2 Answers 2

4
<?php

   $array = array(1,2,3,2,4,1,1,2,3);
   getFor(1,$array);

   function getFor($a,$arr)
   {
     $keys = array_keys($arr, $a);
     $count = count($keys);
     $first = $keys[0];
     $last = $keys[$count-1];
     $str = $first."=".$last;
     echo $str;
   }

?>
Sign up to request clarification or add additional context in comments.

Comments

1

Heres an OOP solution:

class GetFor
{
    private $Foo[];
    public function __construct(
        array $foo, $bar
    ) {
        $this->Foo = array_keys($foo, $bar);
        return $this->Foo[0] . '-' . $this->Foo[count($this->Foo) -1)];
    }
}

echo new GetFor(
    [0,1,2,3,4,6,3,1,5], 2
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.