简体   繁体   中英

Deleting all array values from a specific offset and on

I have an array that has 120~ or so offsets and I was wondering how you would delete all the values of said array after a certain offset containing a specified string. For example: Offset [68] has the string 'Overflow'. I want to remove everything including 68 and beyond and rebuild the array (with its current sorting in tact).

I tried messing around with slice and splice but I can't seem to get it to return the right values. I was also thinking of just grabbing the offset number that contains 'Overflow' and then looping it through a for statement until $i = count($array); but that seems a little more intensive than it should be.

Would this be the best way? Or is there some function to do this that I'm just using wrong?

使用array_slice()

$desired = array_slice($input, 0, $upTo);

First you need to find the string occurrence in the array, and, if the value was found, trim the array from that point;

function removeString($string, $array)
{
  # search for '$string' in the array
  $found = array_search($string, $array);

  if ($found === false) return $array; # found nothing

  # return sliced array
  return array_slice($array, $found);
}

And if you need to make the array sequential (to avoid surprises due to missing offsets), you can always add in the first line $array = array_values($array) . This will reorganize the array values in a new array with ordered offsets: 0, 1, 2, 3, 4...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM