PHP array find two numbers are one after another

PHP array find two numbers are one after another



I have a sorted array with these stop_ids.



1,
6,
13,
18,
31,



I just want to find given first search value(6) is before the second given value(31). I tried something like this. That means the find order should be, first (6) then (13) not (13) first and (6) then.


foreach ($parent_array as $key => $value)
$k = $key;
sort($routes); //another array with above values(stop_ids)
$st = 0;
foreach ($routes as $key => $value)
if($st == 1)
unset($parent_array[$k]);
break;

elseif($value->stop_id == 31)
$st = 1;
continue;



return $parent_array;



I can provide two values. Here I used second value(31) only. Any help ???






If the array is sorted then can't you just check that it contains both elements? The lowest will always be first.

– iainn
Sep 15 '18 at 9:24






@iainn Hey.. these 1,6,13 (according to the below answer)always not be like. sometimes that array may looks like 2,12,9,10.... I just want to know if my given first value is 6, is that before my second value 31

– Ravi_R
Sep 15 '18 at 9:31







So the array isn't sorted? Or are there two arrays? Your question isn't very clear.

– iainn
Sep 15 '18 at 9:38







No. I sorted the array to get the number appearance order. OK just ignore that sorting part. I just want to know if my given first value is (6), is that before my second value (31)

– Ravi_R
Sep 15 '18 at 9:42






Ok, so what's wrong with the answer you've got? That's exactly what it does.

– iainn
Sep 15 '18 at 9:42




1 Answer
1



Get array keys, under which is every number is located and compare this keys:


function firstNumberFirst($array, $first_number, $second_number)

return array_search($first_number, $array) < array_search($second_number, $array);


$a = [1, 6, 13, 18, 31];
var_dump(
firstNumberFirst($a, 6, 13),
firstNumberFirst($a, 6, 18),
firstNumberFirst($a, 13, 6)
);



If array is not zero-indexed - apply array_values first.


array_values






Hey.. these 1,6,13 always not be like that way. sometimes that array may looks like 2,12,9,10.... I just want to know if my given first value is 6, is that before my second value 31

– Ravi_R
Sep 15 '18 at 9:29







Ahh.. Thanks man.. This is the way !!! :)

– Ravi_R
Sep 15 '18 at 9:46



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế