1

I need one help. I need to remove value from multiple array by matching the key using PHP. I am explaining my code below.

$str="ram,,madhu,kangali";
$strid="1,2,,3";
$arr=explode(",",$str);
$arrId=explode(",", $strid);

I have two array i.e-$arr,$arrId which has some blank value. Here I need if any of array value is blank that value will delete and the same index value from the other array is also delete.e.g-suppose for $arr the 1 index value is blank and it should delete and also the the first index value i.e-2 will also delete from second array and vice-versa.please help me.

0

3 Answers 3

2

try this:

 $str="ram,,madhu,kangali";
$strid="1,2,,3";
$arr=explode(",",$str);
$arrId=explode(",", $strid);
$arr_new=array();
$arrId_new=array();
foreach ($arr as $key => $value) {
  if(($value != "" && $arrId[$key] != "")){
    array_push($arr_new, $value);
    array_push($arrId_new, $arrId[$key]);
  }
}

var_dump($arr_new);
var_dump($arrId_new);
Sign up to request clarification or add additional context in comments.

2 Comments

its giving the output like {"0":"ram","3":"kangali"} . where its coming in different format.
i need like this ["ram","kangali"].
2

Try:

foreach ($arr as $key => $value) {
    if ( empty($value) || empty($arrId[$key]) ) {
        unset($arr[$key]);
        unset($arrId[$key]);
    }
}

Comments

1

You can zip both lists together and then only keep entries where both strings are not empty:

$zipped = array_map(null, $arr, $arrId);
$filtered = array_filter($zipped, function ($tuple) {
    return !empty($tuple[0]) && !empty($tuple[1]);
});
$arr = array_map(function($tuple) {return $tuple[0];}, $filtered);
$arrId = array_map(function($tuple) {return $tuple[1];}, $filtered);

Link to Fiddle

2 Comments

Its format is different like array(2) { [0]=> string(3) "ram" [3]=> string(7) "kangali" } coming.
Just do $arr = array_values($arr) to rearrange the keys