Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

PHP - If array key exist and not empty

I got the following array

(
    [0] => 1
    [1] => John Doe
    [2] => john
    [3] => [email protected]
    [4] => lorem
    [5] => Lorem, Ipsum Dolor Sit Amet
)

Basically I am reading those values from CSV file, I want to validate the data before inserting into the database, here is the basic validation i want to apply

Here is what i am doing:

if (count($value) == 6) {
    $params = array(
        'id' => array_key_exists(0, $value) && !empty($value[0]) ? $value[0]: null,
        'name' => array_key_exists(1, $value) && !empty($value[1]) ? $value[1]: null,
        'username' => array_key_exists(2, $value) && !empty($value[2]) ? $value[2]: null,
        'email' => array_key_exists(3, $value) && !empty($value[3]) ? $value[3]: null,
        'password' => array_key_exists(4, $value) && !empty($value[4]) ? $value[4]: null,
        'position' => array_key_exists(5, $value) && !empty($value[5]) ? $value[5]: null
    );
}

I am wondering, what would be the better way of handling this? what i don't like is the repetition, Probably i can solve by putting it inside a loop, I want to know from you how would you do it?

Thanks.

Upvotes: 2

Views: 344

Answers (2)

Pedro Silva
Pedro Silva

Reputation: 263

one way is to use array_merge(), you can make a function like this:

public function merge_my_array($params = []){

  return array_merge(
    [
      'id' => null,
      'name' => null,
      'username' => null,
      'email' => null,
      'password' => null,
      'position' => null
    ], $params);
}

now if you call the function like this:

$array = merge_my_array(['id'=>1, 'name'=>'John', 'email'=>'[email protected]']);

variable $array will have:

id 1, name John, email [email protected] and all the other attributes null.

And if you call the function without passing parameters it is ok, its not mandatory and will return an array with all those 6 attributes all null. Like this:

$array = merge_my_array();

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

Just simply use array_map() to check if the value isn't empty and array_combine() it with the keys, like this:

if(count($value) == 6) {
    $params = array_combine(["id", "name", "username", "email", "password", "position"], array_map(function($v) {
        return ( !empty($v) ? $v : NULL );
    }, $value));
}

Upvotes: 6

Related Questions