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));