2

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?

asked Mar 2, 2012 at 19:34
4
  • 3
    I'd think that array_values is useless here. With PHP 5.4 you can do $item->xpath($s)[0] Commented Mar 2, 2012 at 19:35
  • 1
    Why do you want to avoid a variable here? Whats wrong with $results = $item->xpath($s); $var = (string) $results[0];? Commented Mar 2, 2012 at 19:37
  • @knittl syntax error, unexpected '[' in /home/... line 211 when I tried your version. My php version might be slightly older than 5.4 Commented Mar 2, 2012 at 19:57
  • @TecBrat: array subscript on function calls was only added with PHP 5.4 (released today) Commented Mar 2, 2012 at 20:19

3 Answers 3

10

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));
answered Mar 2, 2012 at 19:43
2
  • 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. Commented Mar 2, 2012 at 20:01
  • 1
    There is also an end() which will get you the last element. Commented Mar 2, 2012 at 20:04
0

I believe this gives the same result.

$var=array_shift($item->xpath($s));
answered Mar 2, 2012 at 19:39
0
$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.

answered Oct 24, 2012 at 22:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.