I have two sets of arrays coming from $_POST. Keys for both will be numeric and the count will be the same, since they come in pairs as names and numbers:
$_POST[names]
(
    [0] => First
    [1] => Second
    [2] => 
    [3] => Fourth
)
$_POST[numbers]
(
    [0] => 10
    [1] => 
    [2] => 3
    [3] => 3
)
Now I need to combine those two, but remove each entry where either values are missing.
The result should be something like:
$finalArray
(
    [First] => 10
    [Fourth] => 3
)
Post data is dynamically created so there might be different values missing based on user input.
I tried doing something like:
if (array_key_exists('names', $_POST)) {
        $names = array_filter($_POST['names']);
        $numbers = array_filter($_POST['numbers']);
        if($names and $numbers) {
           $final = array_combine($names, $numbers);
        }
    }
But I can't seem to filter it correctly, since its giving me an error:
Warning: array_combine(): Both parameters should have an equal number of elements
How about using array_filter with ARRAY_FILTER_USE_BOTH flag on?
<?php
    $array1 = [
        0 => "First",
        1 => "Second",
        2 => "",
        3 => "Fourth",
    ];
    $array2 = [
        0 => 10,
        1 => "",
        2 => 3,
        3 => 3,
    ];
    var_dump(array_filter(array_combine($array1, $array2), function($value, $key) {
        return $key == "" || $value == "" ? false : $value;
    }, ARRAY_FILTER_USE_BOTH ));
/*
Output:
array(2) {
  ["First"]=>
  int(10)
  ["Fourth"]=>
  int(3)
}
*/
                        Here's a fun way:
$result = array_flip(array_flip(array_filter(array_combine($_POST['names'],
                                                           $_POST['numbers']))));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With