Denoteone
Denoteone

Reputation: 4055

Cleaning up array elements from a form

I have a form that uses inputs to create and array. The inputs are not all required but at least one is.

<form method="post" action="process.php">
    <input type="text" name="MAC[]" maxlength="12" />
    <input type="text" name="MAC[]" maxlength="12" />
    <input type="text" name="MAC[]" maxlength="12" />
    <input type="text" name="MAC[]" maxlength="12" />
    <input class="submitbg" type="submit" value="Register" name="submit"/>
 </form>

Now on process.php I want to loop through the array remove two types of special characters : ; then make all upper case, and verify there are only 12 characters and then serialize the arrray.

$my_array = $_POST['MAC'];
foreach ($my_array as $val){
    $val = strtoupper($val);
    $val = str_replace(";","",$val);
    $val = str_replace(":","",$val);
    $val = trim($val);
    if (strlen($val) != 12)){
        $valid = false;
        $error = "Your MAC address is not 12 characters long";
    }
}
$mac_addresses = serialize($my_array);

// if valid is not false do something with the cleaned up array.

The questions:

  1. Will my foreach loop save the updated values back into the array?
  2. How to check to make sure there is at least one array value?

Upvotes: 0

Views: 221

Answers (4)

Alessandro Vermeulen
Alessandro Vermeulen

Reputation: 1331

I am just not sure if my foreach loop updates and resaves the values each time

If you want to save the values you should change your loop so that it looks something like this:

foreach ($my_array as $idx => $val) {
  ...
  $my_array[$idx] = $val;
}

Of course you could also save the proper value to a separate clean array which you will then use further on in your application.

I also have to check to make sure there is at least one entry.

In theory you do not have to check whether the array contains elements to use the array in a foreach. The thing you need to check though is whether the variable contains an array. Suppose the MAC[] field wasn't submitted to the server you would first get a warning (it might also be an error nowadays) because you are looking up some non-existent index in the array. Secondly you would get an error on your foreach as it works on arrays (or anything that is Traversable). You could fix this with the following check:

if (!empty($_POST['MAC'])) {
  $my_array = $_POST['MAC'];
  if (!is_array($my_array)) {
    // throw some error.
  }
}

Of course you would want to do this validation of your input in a more structured way by providing a validation framework which you can provide validation rules and some input and the validation framework will then handle the validation and most importantly the error messages for you.

Actually could also change the last if-statement to read:

if (!is_array($my_array) && !($my_array instanceof Traversable))

That is if you want to be sure $my_array contains something you can traverse over with foreach. The nasty bit is that the built-in array() isn't Traversable, nasty although understandable.

Upvotes: 2

DShook
DShook

Reputation: 15664

To check to see if you have at least one you should be able to use if(count($my_array) > 1)

Upvotes: 1

HBublitz
HBublitz

Reputation: 680

I'm also not understanding your question /problem. But, looking at your code, you might get the feeling that in the end nothing has happened to your POSTed vars. You're right! :-)

Your cleaned up array at the end of the script is exactly the original array. You might want to achieve something like this: The clean array will contain cleaned values, if they consist of 12 characters.

$my_array = $_POST['MAC'];
$my_clean_array = $_POST['MAC'];
foreach ($my_array as $val) {
        $val = strtoupper($val);
        $val = str_replace(";","",$val);
        $val = str_replace(":","",$val);
        $val = trim($val);
        if (strlen($val) != 12)) {
            $valid = false;
            $error = "Your MAC address is not 12 characters long";
        }
        else {
            $my_clean_array[] = $val;
        }
}
$mac_addresses = serialize($my_clean_array);

Upvotes: 1

Khez
Khez

Reputation: 10350

  1. What's the question?
  2. you can do str_replace(array(';',':'),'',$val);
  3. It's usually better to trim before doing other processing on the same variable due to the overhead involved in processing data you will eventually cut
  4. Consider using break on errors, if you halt execution on one error.
  5. You're not really doing any updates to $my_array.

Consider doing:

foreach($my_array as &$val)

You pass by reference so all updates to $val happen to the actual array. Or:

foreach($my_array as $key=>$val){
    $my_array[$key]=trim($my_array[$key]);

You can also try to create a new array for your sanitized data and then over-write your old array. It all depends on needs.

Upvotes: 1

Related Questions