July 9, 2012
Find the exact word position in string
Question by Joe
Let’s say I have a string.
$string = red,green,blue,yellow,black;
Now I have a variable which is the position of the word I am searching for.
$key = 2;
I want to get the word with the position of 2. In this case, the answer would be blue
.
Answer by biziclop
Answer by Starx
A better way to solve this, would be by converting the string into an array using explode().
$string = ...;
$string_arr = explode(",", $string);
//Then to find the string in 2nd position
echo $string_arr[1]; //This is given by n-1 when n is the position you want.