0

I have a 2-dimensional array and want to delete all elements, whose values are not "Name1". They should keep their index numbers (keys):

Array
(
    [array001] => Array
        (
            [0] => Name1
            [1] => Name2
            [2] => Name3
            [3] => Name1
        )

    [array002] => Array
        (
            [0] => Name2
            [1] => Name1
            [2] => Name4
        )
    [array003] => Array
    ....
)

will output

Array
(
    [array001] => Array
        (
            [0] => Name1
            [3] => Name1
        )

    [array002] => Array
        (
            [1] => Name1
        )
    [array003] => Array
    ....
)

Possible solutions could be achieved with a foreach loop, with preg_replace, when the array is converted into a string: $array = print_r($array,true);

4 Answers 4

1

none of them is working..

I found the solution by myself:

foreach($array as $key => $value) {
  foreach($value as $innerkey => $innervalue){
    if($innervalue != 'Name1'){
      unset($array[$key][$innerkey]);
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach($array as $key => $value) {

    foreach ($value as $string) {

        if ($string !== "Name1") {
            unset($string);
        }
    }
}

Comments

0

try this:

function removeElementDifferentValue($array, $value){
     foreach($array as $subKey => $val){
          if($val != $value){
               unset($array[$subKey]);
          }
     }
     return $array;
}

$array = removeElementWithValue($array, 'Name1');

Comments

0
foreach($array as $key1 => $val1) {
    foreach($val1 as $key2 => $val2) {
        if(strcmp($val2,"Name1") != 0) {
            unset($array[$key1][$key2]);
        }
    }
}

3 Comments

unfortunately not working, see my solution I found myself ;) Fatal error: Cannot unset string offsets
Your code is the same as mine, you just use a different string comparison.
Sorry, yes you are right, I don't know what caused the error ;) Thanks anyway!

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.