0

I have this array:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
Array
(
    [0] => Array
        (
            [id] => 191
            [range] => today
        )

    [1] => Array
        (
            [id] => 190
            [range] => today
        )

    [2] => Array
        (
            [id] => 189
            [range] => in last week
        )

    [3] => Array
        (
            [id] => 180
            [range] => in last week
        )

    [4] => Array
        (
            [id] => 170
            [range] => in last week                  <- this
        )
)
*/

I'm trying to get the vale of range which is last item. in this case it is in last week. Here is my code:

foreach ( $results as $item ) {
    $last_range_item = $item[range];
}

My approach should work, but there is a lot of useless processes and overwriting. So is there any better way?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111

2 Answers2

2

You can get the last range using different ways.

 1. echo $result[count($result)-1]['range'];
 2. $new = array_column($arr, 'range'); echo $new[count($new)-1];
 3. and so on.... 
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
2

Very simple way:

echo end(end($arr));
ksno
  • 487
  • 1
  • 4
  • 21
  • @Stack do it in steps `$temp = end($results); echo end($temp);` – splash58 May 31 '16 at 10:00
  • @Stack [Take a look at this](http://stackoverflow.com/questions/2354609/strict-standards-only-variables-should-be-passed-by-reference). You can also suppress error message using `@` operator, but thats not nice work-around tho. – ksno May 31 '16 at 10:00