开发者

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 th开发者_如何学Cis that I'm just using wrong?


Use 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜