Jack Casas
Jack Casas

Reputation: 984

PHP: How to get the last value of an array

The following PHP code I have:

foreach ($resources as $resource)
{
    // Iterates on the found IDs
    //echo 'Name of field: ' . $resource . ' - Value: ' . $resource->attributes() . '<br />';
    echo '<tr><td>'.$resource->attributes().'</td></tr>';
}

Returns:

1
2
3
4
5
6
7
8

I only want to get the value of the last item: 8 I've tried using:

echo end(end($resources->attributes()));

But this returns: 1

Any ideas on how I can get 8 value?

Thanks

Upvotes: 2

Views: 5908

Answers (8)

Tony Stark
Tony Stark

Reputation: 8084

Try to use end(),

end($resources)->attributes();

may this help you.

Upvotes: 6

user2414187
user2414187

Reputation: 1

$array[]=array( 'id'=>1, 'value'=>'val1' );

    $array[]=array( 'id'=>2, 'value'=>'val2' );

    $array[]=array( 'id'=>3, 'value'=>'val3' );

    $array[]=array( 'id'=>4, 'value'=>'val4' );

simplest way to get last value :

    $numb = count($array)-1;
    echo $array[$numb]['value'];

Upvotes: 0

Glitch Desire
Glitch Desire

Reputation: 15023

You're calling end twice, so the outermost end function is only working on a single element (return of inner end function). Try this instead:

echo end($resources)->attributes;

If your attributes is a function rather than a variable, you'd call:

echo end($resources)->attributes();

Live demo here

Upvotes: 0

ZeroGS
ZeroGS

Reputation: 139

You could use

$yourvar = count($yourarray)

than you could call it like

echo $yourarray[$yourvar];

that would directly out print last value in your array

Upvotes: -1

wpenton
wpenton

Reputation: 91

you could also use array_reverse() and then use $my_array[0]

      <?php
          $my_array = array(1,2,3,4,5,6,7,8);
          array_reverse($my_array);
          echo $my_array[0]; // echoes 8
      ?>

Upvotes: 3

Vivek Sadh
Vivek Sadh

Reputation: 4268

This should work:-

end($resources)->attributes()

Upvotes: 0

Florian Klein
Florian Klein

Reputation: 8915

What you should do is:

end($resources)->attributes();

Upvotes: 2

deceze
deceze

Reputation: 522015

end($resources)->attributes()

Upvotes: 5

Related Questions