I'm trying to keep my code nice and elegant. Any way to make this if statement shorter?
if(strlen($cname) > 100) {
}
if(strlen($cowner) > 100) {
}
if(strlen($cemail) > 200) {
}
if(strlen($cpassword) > 100) {
}
I can't do this because I want to print out a specific message for each if statement:
if(strlen($cname) > 100 || strlen($cowner) > 100 || strlen($cemail) > 200 || strlen($cpassword) > 100) {
// I want to print out a message like email is too long not just one of these strings is too long
}
Frankly, I think you've got the most elegant solution for what you are trying to do.
You can use a loop to reduce the number of lines. Here is an optimized solution even when you have more 10 fields to check:
Declare an array of fields and loop through it
$fields = array("cname" => 100, "cowner" => 100, "cemail" => 200, "cpassword" => 100); // key as field name and value as maximum limit - new values can be added here.
foreach($fields as $field => $length) {
if(strlen(${$field}) > $length) {
die("$field field can only contain $length characters");
}
}
Edit: You can also keep all errors in an array and then print all the errors on your page.
$errors = array();
foreach($fields as $field => $length) {
if(strlen(${$field}) > $length) {
$errors[] = "$field field can only contain $length characters";
}
}
print_r($errors);
You already using an optimized code. But you can optimize it little bit more for showing error message. Like below:
$invalidFieldName = '';
$invalidFieldLength = 100;
if (strlen($cname) > 100) {
$invalidFieldName = 'CNAME';
} elseif (strlen($cowner) > 100) {
$invalidFieldName = 'COWNER';
} elseif (strlen($cemail) > 200) {
$invalidFieldName = 'CEMAIL';
$invalidFieldLength = 200;
} elseif (strlen($cpassword) > 100) {
$invalidFieldName = 'CPASSWORD';
}
if ($invalidFieldName != '') {
echo $invalidFieldName." should be greater than ".$invalidFieldLength;
}
I am not really sure if it will help you but I hope it will help you.
Related
I am making seeders for a M:M relation where I would like to attach 1 Widget to WorkspaceItem in 90% of cases, other 5% 2, last 5% 3.
$widgets = Widget::all();
$workspaceItems = WorkspaceItem::all();
foreach ($workspaceItems as $workspaceItem) {
$numberBetween = $faker->numberBetween(0, 100);
if ($numberBetween > 95) {
$widgetsToSeed = $widgets->random(3);
} else if ($numberBetween > 90 && $numberBetween <= 95) {
$widgetsToSeed = $widgets->random(2);
} else {
$widgetsToSeed = $widgets->random();
}
foreach ($widgetsToSeed as $widget) {
$workspaceItem->widgets()->attach($widget->id, [...]);
}
}
Note: I can't use sync() because I have additional properties for pivot table.
If I dd($widgetsToSeed), I indeed get random widgets. But as soon as it enters the loop and I dd($widget) I don't get the model, but just true. What seems to be the problem?
I think you should be able to just do:
$workspaceItem->widgets()->saveMany($widgetsToSeed);
And by that you don't even need the last foreach loop. To always receive a collection (even with only one element), you can also add random(1) in your last else statement. With some minor simplifications it might look like this:
foreach ($workspaceItems as $workspaceItem) {
$numberBetween = $faker->numberBetween(0, 100);
if ($numberBetween > 95) {
$widgetsToSeed = $widgets->random(3);
} else if ($numberBetween > 90) {
$widgetsToSeed = $widgets->random(2);
} else {
$widgetsToSeed = $widgets->random(1);
}
$workspaceItem->widgets()->saveMany($widgetsToSeed);
}
if($_SESSION['valueofdie1'] != 0 && $_SESSION['valueofdie2'] != 0 && $_SESSION['valueofdie3'] != 0 && $_SESSION['valueofdie4'] != 0 && $_SESSION['valueofdie5'] != 0)
{
if((($_SESSION['valueofdie1'] == $_SESSION['valueofdie2']) && ($_SESSION['valueofdie2'] == $_SESSION['valueofdie3']||$_SESSION['valueofdie4']||$_SESSION['valueofdie5'])) || (($_SESSION['valueofdie1'] == $_SESSION['valueofdie3']) && ($_SESSION['valueofdie3'] == $_SESSION['valueofdie4']||$_SESSION['valueofdie5'])) || (($_SESSION['valueofdie1'] == $_SESSION['valueofdie4']) && ($_SESSION['valueofdie4'] == $_SESSION['valueofdie5']))
|| (($_SESSION['valueofdie2'] == $_SESSION['valueofdie3']) && ($_SESSION['valueofdie3'] == $_SESSION['valueofdie4']||$_SESSION['valueofdie5'])) || (($_SESSION['valueofdie2'] == $_SESSION['valueofdie4']) && ($_SESSION['valueofdie4'] == $_SESSION['valueofdie5']))
|| (($_SESSION['valueofdie3'] == $_SESSION['valueofdie4']) && ($_SESSION['valueofdie4'] == $_SESSION['valueofdie5'])))
{
if($_POST['choose'] == 'choose 3oaK')
{
$_SESSION['g'] = 5;
$_SESSION['scoretkind'] = $_SESSION['valueofdie1'] + $_SESSION['valueofdie2'] + $_SESSION['valueofdie3'] + $_SESSION['valueofdie4'] + $_SESSION['valueofdie5'];
unset($_SESSION['3oaKBut']);
echo '<input type="hidden" name="choose" value="Clear" onLoad="form.submit();">';
$_POST['sub'] = 'reset';
$_POST['choose'] = '';
}
if(empty($_SESSION['g']))
{
$_SESSION['3oaKBut'] = '<input type="submit" name="choose" value="choose 3oaK">';
echo $_SESSION['3oaKBut'];
}
}
}
if($_SESSION['g'] == 5)
{
echo $_SESSION['scoretkind'];
}
So here is the code we have. We are trying to check if 3 of the 5 die values are equal. If they are equal we echo out a button that allows the user to choose to score his 3 of a kind, which is the total of all of the dice. Everything works except in some cases the 3 of a kind button would echo out when there isnt a 3 of a kind. Halp PLS
I'm sorry I didn't answer your question by actually solving your bug, but I think your code is hard to read and your approach makes it cumbersome to program all the rules.
General advice: Put $_SESSION['valueofdie1'] and the other dice into an array of values. That's much easier to work with. After that, it should be pretty easy to check how many times each value occurs. Even when you keep your approach, you could make variables like $die1, which is already a lot shorter and more readable than $_SESSION['valueofdie1'].
But with an array, you could roughly start like this:
// Put all dice into an array.
$dice = array(
$_SESSION['valueofdie1'],
$_SESSION['valueofdie2'],
etc.... );
// Count how many times each die is rolled.
$diceCount = array();
foreach($dice as $die) {
$count = 0;
if (isset($diceCount[$die])) {
$count = $diceCount[$die];
}
$diceCount[$die] = $count + 1;
}
// Check possible results simply by looking at those counts.
// If one die value is rolled 5 times, it's Yahtzee...
if (array_search(5, $diceCount) !== false) {
echo 'Yahtzee!';
}
if (array_search(4, $diceCount) !== false) {
echo 'Four of a kind';
}
// Full house takes two types.
if (array_search(3, $diceCount) !== false && array_search(2, $diceCount) !== false) {
echo 'Full house';
}
for ($diceCount as $die => $count) {
echo "$count times $die";
}
... etc ...
You'll need to expand this list, and take some other rules into account. After all, a Yahtzee could also count as a Four of a Kind. But by checking all those rules, you can generate a new array of possible combinations, which you can check against the previously chosen options. And the outcome of that determines which options the player can choose.
I'm currently writing up a function in order to validate a URL by exploding it into different parts and matching those parts with strings I've defined. This is the function I'm using so far:
function validTnet($tnet_url) {
$tnet_2 = "defined2";
$tnet_3 = "defined3";
$tnet_5 = "defined5";
$tnet_7 = "";
if($exp_url[2] == $tnet_2) {
#show true, proceed to next validation
if($exp_url[3] == $tnet_3) {
#true, and next
if($exp_url[5] == $tnet_5) {
#true, and last
if($exp_url[7] == $tnet_7) {
#true, valid
}
}
}
} else {
echo "failed on tnet_2";
}
}
For some reason I'm unable to think of the way to code (or search for the proper term) of how to break out of the if statements that are nested.
What I would like to do check each part of the URL, starting with $tnet_2, and if it fails one of the checks ($tnet_2, $tnet_3, $tnet_5 or $tnet_7), output that it fails, and break out of the if statement. Is there an easy way to accomplish this using some of the code I have already?
Combine all the if conditions
if(
$exp_url[2] == $tnet_2 &&
$exp_url[3] == $tnet_3 &&
$exp_url[5] == $tnet_5 &&
$exp_url[7] == $tnet_7
) {
//true, valid
} else {
echo "failed on tnet_2";
}
$is_valid = true;
foreach (array(2, 3, 5, 7) as $i) {
if ($exp_url[$i] !== ${'tnet_'.$i}) {
$is_valid = false;
break;
}
}
You could do $tnet[$i] if you define those values in an array:
$tnet = array(
2 => "defined2",
3 => "defined3",
5 => "defined5",
7 => ""
);
I want to refactor this piece of code, it takes input from a form, then sanitizes the input, then it checks if its empty, or too short. It does this for title, content and tags. It stores an errors encountered in an array called errors.
I want to make a function, something like this:
function validate_input($args)
Except I'm unsure as to how I'm going to implement it, and how it'll build up an error list.
(I know I can use something like PEAR QUICKFORM or php-form-builder-class, so please don't mention 'oh use Class xyz').
$title = filter_input(INPUT_POST, 'thread_title', FILTER_SANITIZE_STRING,
array('flags' => FILTER_FLAG_STRIP_HIGH|FILTER_FLAG_STRIP_LOW ));
$content = filter_input(INPUT_POST, 'thread_content');
$tags = filter_input(INPUT_POST, 'thread_tags');
# title here:
if (is_null($title) || $title == "") # is_null on its own returns false for some reason
{
$errors['title'] = "Title is required.";
}
elseif ($title === false)
{
$errors['title'] = "Title is invalid.";
}
elseif (strlen($title) < 15)
{
$errors['title'] = "Title is too short, minimum is 15 characters (40 chars max).";
}
elseif (strlen($title) > 80 )
{
$errors['title'] = "Title is too long, maximum is 80 characters.";
}
# content starts here:
if (is_null($content) || $content == "")
{
$errors['content'] = "Content is required.";
}
elseif ($content === false)
{
$errors['content'] = "Content is invalid.";
}
elseif (strlen($content) < 40)
{
$errors['content'] = "Content is too short, minimum is 40 characters."; # TODO: change all min char amounts
}
elseif (strlen($content) > 800)
{
$errors['content'] = "Content is too long, maximum is 800 characters.";
}
# tags go here:
if (is_null($tags) || $tags == "")
{
$errors['tags'] = "Tags are required.";
}
elseif ($title === false)
{
$errors['tags'] = "Content is invalid.";
}
elseif (strlen($tags) < 3)
{
$errors['tags'] = "Atleast one tag is required, 3 characters long.";
}
var_dump($errors);
Should be pretty simple if understood your problem correctly and you want to validate and sanitize only those three variables.
function validateAndSanitizeInput(Array $args, Array &$errors) {
//validation goes in here
return $args;
}
In this case the errors array is passed by reference so you'll be able to get the error messages from it after the function has been called.
$errors = array();
$values = validateAndSanitizeInput($_POST, $errors);
//print $errors if not empty etc.
By the way you could replace "is_null($content) || $content == """ with "empty($content)"
when i try to filter all these parameters php only enters in the first if conditions, ignoring all others conditions.
if($t_red<0){
$t_red=0;
}
else if($t_red>256){
$t_red=255;
}
else if($t_green<0){
$t_red=0;
}
else if($t_green>256){
$t_red=255;
}
if($t_blue<0){
$t_red=0;
}
if($t_blue>256){
$t_red=255;
}
if($t_red<0){
$t_red=0;
}
Probably best suited if ran through a filtering function.
function setParam($param) {
if($param < 0) {
$param = 0;
} elseif($param > 256) {
$param = 255;
}
return $param;
}
$t_green = setParam($t_green);
$t_red = setParam($t_red);
$t_blue = setParam($t_blue);
You could also use pass-by-reference if necessary.
It's not clear what you're trying to do, but I think that you would want to remove the else before the third if statement and add an else before the sixth if statement.
$t_red=$t_red<0?0;$t_red;
$t_red=$t_red>=256?255;$t_red;
//are you sure you're modifying t_red here? and not t_green?
$t_red=$t_green<0?0;$t_red;
$t_red=$t_green>=256?255;$t_red;
//are you sure you're modifying t_red here? and not t_blue?
$t_red=$t_blue<0?0;$t_red;
$t_red=$t_blue>=256?255;$t_red;
a successfully met condition of an if (or following else if) statement will ignore all else if/else statements that immediately follow it, but the if statements afterwards are executing - You can verify this by adding echo statement to each one . Could it perhaps be because all your variable assignments are for $t_red so no action is taken on $t_green or $t_blue?
if($t_red < 0)
{
$t_red = 0;
}
else if($t_red > 255) //Original won't catch it if it is == to 256, have to do either >= 256 or > 255
{
$t_red = 255;
}
if($t_green < 0)
{
$t_green = 0;
}
else if($t_green > 255)
{
$t_green = 255;
}
if($t_blue < 0)
{
$t_blue = 0;
}
else if($t_blue > 255)
{
$t_blue = 255;
}
Andrew Sledge's answer is the best though, but I did correct the fact that it would miss correcting the value if it was == to 256, which wouldn't be caught by just $var > 256, and thus would be in error if the value has to be between 0 and 255.