PHP: Get first and last element entries in array and it's keys

782

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.

173

Answer

Solution:

<?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;
   }

?>
614

Answer

Solution:

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
);

People are also looking for solutions to the problem: javascript - jQuery GET request to PHP failing although PHP is fetching the data

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.