Jacob
Jacob

Reputation: 2071

Check if the variables passed to a function is empty

Im working on a register function that will register users into the database.

I want a checker in that function that checks if any of the arguments are empty. I've simplified the problem, so this is not the retail look.

<?php

create_user($_POST["username"], $_POST["epost"]);

function create_user($username, $epost){

// Pull all the arguments in create_user and check if they are empty


    // Instead of doing this:

   if(empty($username) || empty($epost)){

    }

}

Reason for making this is so i can simply add another argument to the function and it checks automatically that it isnt empty.

Shorted question:

How do I check if all the arguments in a function isnt empty?

Upvotes: 0

Views: 498

Answers (2)

bystwn22
bystwn22

Reputation: 1794

You can use array_filter and array_map functions also.
For example create a function like below

<?php
function isEmpty( $items, $length ) {
  $items  = array_map( "trim", $items );
  $items  = array_filter( $items );

  return ( count( $items ) !== (int)$length );
}
?>

the above function accepts two parameters.

$items = array of arguments,  
$length = the number of arguments the function accepts.  

you can use it like below

<?php
create_user( $_POST["username"], $_POST["epost"] );

function create_user( $username, $epost ) {
  if ( isEmpty( func_get_args(), 2 ) ) {
    // some arguments are empty
  }
}
?>

Upvotes: 0

xd6_
xd6_

Reputation: 483

function create_user($username, $epost){

    foreach(func_get_args() as $arg)
    {
    //.. check the arg
    }
}

Upvotes: 3

Related Questions