简体   繁体   中英

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

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.

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

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