0

How can I loop through an array like this and retrieve the id and echo it to the screen? Also how can I do a loop and find the one with the highest id?

Array
(
    [articles] => Array
        (
            [0] => Array
                (
                    [id] => 650
                )

            [1] => Array
                (
                    [id] => 649
                )

            [2] => Array
                (
                    [id] => 645
                )

            [3] => Array
                (
                    [id] => 399
)
);

3 Answers 3

2

You can do this with foreach

foreach ($array['articles'] as $value)
{
   echo "Id is: ".$value['id'];
}

And you can get with max() function:

foreach($array['articles'] as $article)
{
    $ids[] = $article['id'];
}
echo "Max Id is: ".max($ids);

Or you can do get value and max id with one foreach.

foreach($array['articles'] as $article)
{
    echo "Id is: ".$article['id'];
    $ids[] = $article['id'];
}

echo "Max Id is: ".max($ids);
Sign up to request clarification or add additional context in comments.

4 Comments

Its echo is this: Id is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: ArrayId is: Array
Sorry, i missed. Updated!
Your max function will throw the error @Bora for that array <b>Notice</b>: Array to string conversion
Aow! You right. Your array is multidimensional. You can get with foreach again. Updated!
0

Say $arr['articles'] contains your array.Then using a foreach you can loop through the array and just echo it.

$arr = array('articles' => array(
                                 '0' => array('id' => 650),
                                 '1' => array('id' => 649),
                                 '2' => array('id' => 645),
                                 '3' => array('id' => 399)
                                )
           );
foreach($arr['articles'] as $val){
  echo $val['id'].'</br>';
}

1 Comment

It just echos: ArrayArrayArrayArrayArrayArrayArrayArray
0

Try

foreach ($arrayvar['articles'] as $value)
{
   echo $value['id']."<br>";
}

Comments

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.