-2

how to search array by specifying the index to start search from in php

for example: Assuming

$needle_to_search = 5;
$array_to_search = [6,8,4,9,7,5,9,4,5,9,3,5,4,6,7];
$index_to_start_search_from = 5;
$key = array_search($needle_to_search, $array_to_search, $index_to_start_search_from);

is there any function that can implement above pseudo code so that $key will return index: 8

what i mean is that i want to start the search from index 6 so that it returns index 8=> which has the value 5, since value 5 is my aim to search in the array.

myckhel
  • 800
  • 3
  • 15
  • 29
  • 1
    Can you provide the example array with the key you want to start at as it would save the time of the people that are trying to answer your question. Though, maybe [this](http://php.net/manual/en/function.array-search.php#116635) might help. – Script47 Apr 30 '18 at 10:32
  • values provided – myckhel Apr 30 '18 at 10:41

1 Answers1

1

i think you can do with array_slice.

$needle_to_search = 5;
$array_to_search = [6,8,4,9,7,5,9,4,5,9,3,5,4,6,7];
$index_to_start_search_from = 6;

// output

Array
(
    [0] => 6
    [1] => 8
    [2] => 4
    [3] => 9
    [4] => 7
    [5] => 5
    [6] => 9
    [7] => 4
    [8] => 5
    [9] => 9
    [10] => 3
    [11] => 5
    [12] => 4
    [13] => 6
    [14] => 7
)

// return 5
echo array_search($needle_to_search, $array_to_search);

// return 8
echo array_search($needle_to_search, array_slice($array_to_search, $index_to_start_search_from, null, true));
Anfath Hifans
  • 1,588
  • 1
  • 11
  • 20