1

Is it possible to find the last occurrence of a value in an array element starting at a specific index value. I have found a partial solution in this post [How can I find the key of the last occurrence of an item in a multidimensional array? but it doesn't allow for starting at a specific index. I am looping thru an array matching an 'id' number. If the 'id' number doesn't exist in the current array index, I would like to search back from that point finding the last occurrence of that value.

 $last = "";
  foreach($arr as $key => $array) {
    if ( $array['id'] === $id) {
    $last = $key;
   }
   }
  echo $last."\n\n";
1
  • is $arr has numerical indexes? Commented May 20, 2016 at 18:01

2 Answers 2

1

If the array has numeric indexes, you can do that with usual for loop

$last = false;
for($i = $start; $i >= 0; $i--) {  // $start - index to start look up
  if ( $arr[$i]['id'] === $id) {
     $last = $i; 
     break;                        // if key is found, stop loop
  }
}

if($last !== false)
  echo $last."\n\n";
else
  echo "Not found" . "\n";
Sign up to request clarification or add additional context in comments.

2 Comments

Works great with one problem, would there be a reason the found last index would be 1 off. When executed and I review the values of the array at the $last, they are 1 off or showing the values for the next array. If I use $last-1 it skips the desired array and grabs the values of the one before it.
@snowman i was writing by phoe and made many mistakes. Test it now
0
<?php

$myArray = [
  "bus" => "blue",
  "car" => "red",
  "shuttle" => "blue",
  "bike" => "green";
];

$findValue = "blue";

$startIndex = "bus";
$continue = false;
$lastIndex = null;

foreach ($myArray as $key => $value) 
{
  if(!$continue && $key === $startIndex) 
  {
    $continue = true;
  } else if($continue) {
    if($key === $findValue) {
      $lastIndex = $key;
    }
  }
}

Basically what I'm doing here is only checking the index against first index you're trying to find, if its found that index it'll go on to try and compare the current key's value to the one you're trying to specify.

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.