Jump to content

Can this be simplified


acctman

Recommended Posts

I wrote the coding below and was wondering if it could be simplified a bit. what i'm checking for is to see if the user has selected a value for c_state or u_state (both can not be selected at the same time) which ever one is selected the value is saved to $state. Then IF c_state or u_state are both blank then show an error.

 

I'm trying to improve on my coding and not write messy/long coding all the time

 

$state = $_POST['c_state'] != '' || $_POST['u_state'] != '';
if ($_POST['c_state'] && $_POST['u_state'] == '') {
$err = 'select a state<br>';
}

Link to comment
https://forums.phpfreaks.com/topic/122974-can-this-be-simplified/
Share on other sites

You can rewrite it but still you have to run the checks (this is just getting fancy

<?php
$i = 0;
$fields = array("c_state","u_state")
while(empty($state) && $i < count($fields)){
if(!empty($_POST[$fields[$i]])){
$state = $_POST[$fields[$i]];
}
$i++;
}
if(empty($state)){
echo "Error";
}
?>

 

 

Lotta ways to accomplish it do what ever logicaly makes sense to you.

With only two variables to consider, I think a straight-forward if block makes the most sense and is more readible:

 

<?php
if ( empty($_POST['u_state']) && empty($_POST['c_state'])) {
echo "An error occurred! State was not set.";
} elseif (!empty($_POST['u_state'])) {
$state = $_POST['u_state'];
} else {
$state = $_POST['c_state'];
}
?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.