user481913
user481913

Reputation: 1018

Assign key of an array element to a variable

I have the following piece of code and inside the function field_has_input(), I would like to assign the element's key to the errors[]

i.e. errors[]=$key instead of errors[]=$field

The function field_has_input($field) gets called from check_all_fields($_POST)

Hopefully someone can help out.

function field_has_input($field)
{
    global $errors;

    if(!isset($field) || empty($field))
    {
        $errors[]=$field;
    }

}

function check_all_fields($_POST)
{
     global $errors;
    foreach($_POST as $key => $value)
    {
        echo $_POST[$key] . "<br />";
         field_has_input($_POST[$key]);

    }
    //exit;
    var_dump($errors);
    return $errors;
}

Upvotes: 2

Views: 107

Answers (2)

WebChemist
WebChemist

Reputation: 4411

If you want to get an array of values consisting of the $_POST keys that are empty, you can do that with just one line:

$errors = array_keys( array_diff_key( $_POST, array_filter($_POST) ) );
  1. array_filter will remove false, null or empty string values

  2. array_diff_key will compare the original full post array to the filtered version and return only the keys that have been filtered.

  3. array_keys will create an array of values using the array keys of the given array

Example, if:

$arr = array (
     'name'     => 'Bob'
    ,'company'  => ''
    ,'state'    => 'CA'
    ,'phone'    => '' 
);

$errors = array_keys( array_diff_key( $arr, array_filter($arr) ) );
var_dump($errors);

// output:
array(2) {
  [0]=>
  string(7) "company"
  [1]=>
  string(5) "phone"
}

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270599

I would suggest you dispense with the field_has_input() function entirely, and just do the work inside the other loop. Otherwise, you would need to be passing the $key into the inner function. In its current simplicity it is totally unnecessary and adds complexity.

function check_all_fields($_POST)
{
     global $errors;
    foreach($_POST as $key => $value)
    {
        // empty() calls isset() implicitly...
        if (empty($value)) {
          $errors[] = $key;
        }
    }
    //exit;
    var_dump($errors);
    return $errors;
}

Further, I would recommend not using the global errors, but instead passing it to the function. Because $_POST is a superglobal, it is unnecessary to pass it as a parameter to your function. Pass only $errors instead.

function check_all_fields($errors) {
  //  $_POST is already available here...
  foreach($_POST as $key => $value)
  {
    if (empty($value)) {
      $errors[] = $key;
    }
  }
  return $errors;
}

If you must use an inner function, such as if the actual work to be done in field_has_input() is more complex than just checking empty(), pass the $key and check $_POST[$key] inside the function

function field_has_input($key, $errors) {
  if (empty($_POST[$key])) {
    $errors[] = $key;
  }
}

Upvotes: 1

Related Questions