March 2, 2012

Better way to get first element of returned array

Question by TecBrat

I found myself using this:

$var=(string)array_shift(array_values($item->xpath($s)));

where $s is an xpath search string and the return is an array of objects that contain strings.

It works, but I’m not sure it’s the best way to get the data I want.

I could use a tempvar, but I wanted to avoid that.

Any suggestions?

Answer by Mike Purcell

Careful with array_shift, as it will remove the element from the array stack, if you simply want the first value, you can use current:

$var = (string) current($item->xpath($s));

Answer by Starx

I believe this gives the same result.

$var=array_shift($item->xpath($s));

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!