Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP finding second occurrence of a word in array using array_search

Tags:

php

Following code will split a sentence and tell me first occurrence of the word orange. Can you please tell me if it's possible to find the second occurrence of the word orange using a php library function. I could do this by using a for loop, just wondering if array_search library function could do this?

$sentence = "apple orange grapes mango orange banana orange";
$wordarray = preg_split("/[\s,]+/", $sentence); //split by space and comma
$img_pos = array_search('orange', $wordarray);//To get the position of orange
like image 680
D P. Avatar asked Sep 14 '26 19:09

D P.


1 Answers

array_keys() takes a search parameter, so just get the keys for the value you want and check for the second one ([1]):

$img_pos = array_keys($wordarray, 'orange');
print_r($img_pos);
echo $img_pos[1];
like image 191
AbraCadaver Avatar answered Sep 16 '26 10:09

AbraCadaver