简体   繁体   中英

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

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.

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

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

?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM