Reputation: 1837
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 ?
Upvotes: 2
Views: 226
Reputation: 6016
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");
}
Upvotes: -1
Reputation: 154513
Another alternative (this would be way simpler if it were values instead):
array_intersect_key($arr, array_flip(preg_grep('~^VP~', array_keys($arr))));
Upvotes: 0
Reputation: 784878
This works for me:
$prefix = 'VP';
for ($i=0; $i <= count($arr); $i++) {
if (strpos($arr[$i], $prefix) !== 0)
unset($arr[$i]);
}
Upvotes: 0
Reputation: 3730
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]);
}
}
Upvotes: 1
Reputation:
Yes, just use unset()
:
foreach ($array as $key=>$value)
{
if(substr($key,0,2)!=="VP")
{
unset($array[$key]);
}
}
Upvotes: 3