0

I need to remove a certain key of my array since I'm creating a filter for my data.

Array(
   [0]=>Array
      (
        ['Column1'] => 'ABC'
        ['Column2'] => 'xxx'
      )
   [1]=>Array
      (
        ['Column1'] => 'XYZ'
        ['Column2'] => 'xxx'
      )
)

I want to remove the key (meaning the number 2) that has the value 'XYZ'. How can I remove it? I need to remove it because I am filtering the array that was thrown to me by another script and I need to remove the key. I tried using for loop but I do not know how to remove it.

for($z = 0; $z < count($array);$z++)
{
   if($array[$z]['Column1'] == 'XYZ'){
          // how do I remove the record [1] and all of its contents?
  }
}
1
  • you want to get rid of only XYZ or each occurence of column1> Commented Nov 10, 2014 at 10:17

2 Answers 2

3

Use unset()

for($z = 0; $z < count($array);$z++)
{
   if($array[$z]['Column1'] == 'XYZ'){
     unset($array[$z]);
  }
}

You can also do:

foreach($array as &$v) {
  if($v['Column1'] == 'XYZ') {
    unset($v);
  }
}

After using unset() on an array, and as long as you don't need to retain the index values, it is worth doing:

$array = array_values($array);

To reset the array index.

Sign up to request clarification or add additional context in comments.

2 Comments

@marchemike for this solution, after the loop it is good to use $array = array_values($array); to re-base the array indexes as it can leave empty values in indexes where you have unset the value. But that may be your desired result, up to you
Got it working now. +1 for array_values as i need that to reorganize the array as well. Thanks!!
0
foreach ($array as $k => $v)
{
    if ($v['Column1'] == 'XYZ') unset($array[$k]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.