Jump to content

Recommended Posts

I have an array that is displayed using:

 

foreach($page['array'] as $c) {

echo 'some stuff';

}

 

Each has an id .. $c['id'] ... how can I find the highest ID in that array and on that echo have an if statement... so for example the highest ID would read "some stuff HIGHEST".

Link to comment
https://forums.phpfreaks.com/topic/122617-solved-finding-highest-id-in-an-array/
Share on other sites

$maxId = 0;
foreach($page['array'] as $c) {

$maxId = max($maxId,$c['id'])

}
foreach($page['array'] as $c) {

echo 'some stuff';
if ($c['id'] == $maxId) {
  echo "Highest ID";
}

}

 

I don't like it, as it's looping the array twice, but can't think of anything else right now.

 

Perhaps array_walk_recursive()  ??

Could try something like:

 

$highestID = 0;

foreach($page['array'] as $c) {
   if ($c['id'] > $highestID) $highestID = $c['id'];
}

foreach($page['array'] as $c) {
   if ($c['id'] == $highestID) {
       echo 'some stuff';
   } else {
       echo 'some other stuff';
   }
}

 

It's not that efficient as it needs two loops, I dare say there's another way but.. I dont know it...

 

Adam

What about:

$maxId = 0;
$results = array();
foreach($page['array'] as $c) {
     $id = $c['id'];
     if ($maxId < $id) {
          $maxId = $id;
          $results = array();
     }
     if ($maxId == $id) $results[] = $c;
}

echo "Highest id is: " . $maxId;

 

The $results array would have all the results that has the highest ID in case you wanted those too. You can definitely loop through the $results array as well.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.