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?
3 Answers 3
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));
-
Had never seen
current()
before. Thanks. That should be the answer to a lot of "get the first elemen" questions I've see on various PHP forums.TecBrat– TecBrat03/02/2012 20:01:41Commented Mar 2, 2012 at 20:01 -
1There is also an
end()
which will get you the last element.Mike Purcell– Mike Purcell03/02/2012 20:04:29Commented Mar 2, 2012 at 20:04
I believe this gives the same result.
$var=array_shift($item->xpath($s));
$var = $reset($item->xpath($s));
Note that this rewinds the array's internal pointer and returns the first element. The method current
returns the element at the position the pointer happens to be in - it is not guaranteed to always be the first element.
array_values
is useless here. With PHP 5.4 you can do$item->xpath($s)[0]
$results = $item->xpath($s); $var = (string) $results[0];
?syntax error, unexpected '[' in /home/... line 211
when I tried your version. My php version might be slightly older than 5.4