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 ?

1

5 Answers 5

3

Yes, just use unset():

foreach ($array as $key=>$value)
{
  if(substr($key,0,2)!=="VP")
  {
    unset($array[$key]);
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

+1, but I'd use substr() instead of regexp. It is simpler and faster.
why is the "!" in there on line 3?
@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.
@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.
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]);
    } 
}

Comments

0

This works for me:

$prefix = 'VP';
for ($i=0; $i <= count($arr); $i++) {
   if (strpos($arr[$i], $prefix) !== 0)
      unset($arr[$i]);
}

1 Comment

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.
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))));

Comments

-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");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.