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?

3
  • 3
    use array_column($arr, 'range'). using this you can do it. or use echo $result[count($result)-1]['range']. Commented May 31, 2016 at 9:44
  • @FrayneKonok It isn't just containing the last one. Commented May 31, 2016 at 9:45
  • 1
    see updated comment Commented May 31, 2016 at 9:45

2 Answers 2

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.... 
Sign up to request clarification or add additional context in comments.

1 Comment

Check this and let me know is it works for you or not. If not then i have to test it.
2

Very simple way:

echo end(end($arr));

2 Comments

@Stack do it in steps $temp = end($results); echo end($temp);
@Stack Take a look at this. You can also suppress error message using @ operator, but thats not nice work-around tho.

Your Answer

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.