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

http://codepad.org/LA35KzEZ

$a = explode( ',', $string );
echo $a[ $key ];

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!