2

I have an array like this :

array() {
  ["AG12345"]=>
  array() { 

  }
  ["AG12548"]=>
  array() { 

  }
  ["VP123"]=>
  array() { 

  }

I need to keep only arrays with keys which begin with "VP"

It's possible to do it with one function ?

bahamut100
  • 1,795
  • 7
  • 27
  • 38
  • 1
    Possible Duplicate http://stackoverflow.com/questions/2304570/how-to-delete-object-from-array-inside-foreach-loop – CLo Mar 12 '12 at 15:29

5 Answers5

3

Yes, just use unset():

foreach ($array as $key=>$value)
{
  if(substr($key,0,2)!=="VP")
  {
    unset($array[$key]);
  }
}
  • 2
    +1, but I'd use `substr()` instead of regexp. It is simpler and faster. – Minras Mar 12 '12 at 15:31
  • why is the "!" in there on line 3? – crunkchitis May 03 '12 at 16:25
  • @crunkchitis - The condition `substr($key,0,2)!=="VP"` checks to see whether the substring consisting of the first two characters of the string `$key` are identical to the string `"VP"`. In other words, the `!` represents negation. –  May 03 '12 at 16:59
  • 1
    @JackManey - I'm new to php so I didn't know "!==" existed, I only knew about "!=". Turns out it was important to what I was working on. Identical vs. equal. Thanks. – crunkchitis May 04 '12 at 17:28
1

From a previous question: How to delete object from array inside foreach loop?

foreach($array as $elementKey => $element) {
    if(strpos($elementKey, "VP") == 0){
        //delete this particular object from the $array
        unset($array[$elementKey]);
    } 
}
Community
  • 1
  • 1
CLo
  • 3,650
  • 3
  • 26
  • 44
0

This works for me:

$prefix = 'VP';
for ($i=0; $i <= count($arr); $i++) {
   if (strpos($arr[$i], $prefix) !== 0)
      unset($arr[$i]);
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • That's fair you are OP after all :) but to me substr function will also need another function call i.e. strlen to get the length of the prefix. – anubhava Mar 12 '12 at 15:48
0

Another alternative (this would be way simpler if it were values instead):

array_intersect_key($arr, array_flip(preg_grep('~^VP~', array_keys($arr))));
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
-1

This is only a sample how to do this, you have probably many other ways!

// sample array
$alpha = array("AG12345"=>"AG12345", "VP12548"=>"VP12548");
foreach($alpha as $val) 
{
    $arr2 = str_split($val, 2);
    if ($arr2[0] == "VP")
        $new_array = array($arr2[0]=>"your_values");
}
devasia2112
  • 5,844
  • 6
  • 36
  • 56