Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine post values and remove empty

Tags:

arrays

post

php

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

like image 569
Alko Avatar asked Jan 07 '23 05:01

Alko


2 Answers

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)
}
*/
like image 146
revo Avatar answered Jan 16 '23 03:01

revo


Here's a fun way:

$result = array_flip(array_flip(array_filter(array_combine($_POST['names'],
                                                           $_POST['numbers']))));
like image 24
AbraCadaver Avatar answered Jan 16 '23 04:01

AbraCadaver