Fill array regardless if there is empty check - php

So I have the following code:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
if (empty($obj->birthday) || $obj->hire_date) {
$record->fill([
'birthday' => '',
'hire_date' => ''
]);
} else {
$record->fill($arr);
}
} else {
$record->timestamps = false;
}
Where I'm checking if $obj->birthday or $obj->hire_date is empty, and then define them as empty strings, but here is the problem.
I want to be able to call $record->fill($arr) regardless and prepopulate all my fields on the empty check, but for some reason I can't seem to figure out out.
So heres the logic:
Empty hire_date? set as ''.
Empty birthday? set as ''.
Populate the rest of the fields..
Both hire_date and birthday not empty? Populate all fields.

You can try this:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$filllArray = $arr;
if (empty($obj->birthday) {
$record->fill([
'birthday' => ''
]);
unset($filllArray['birthday']);
}
if (empty($obj->hire_date)) {
$record->fill([
'hire_date' => ''
]);
unset($filllArray['hire_date']);
}
$record->fill($filllArray);
} else {
$record->timestamps = false;
}
Update 1: Copy the $arr to $filllArray and update the new array to determine what should be filled or not.

I know you've accepted an answer. This is a slightly different way of achieving the same thing (If I understood the question correctly)
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$fa = [];
empty($obj->birthday) ? $fa['birthday'] = '' : $fa['birthday'] = $obj->birthday;
empty($obj->hire_date) ? $fa['hire_date'] = '' : $fa['hire_date'] = $obj->hire_date;
$merged_arr = array_merge($arr, $fa);
$record->fill($merged_arr);
} else {
$record->timestamps = false;
}

Related

How to check empty condition using PHP combinations?

Here I am having 5 fields:
clgID
empID
startDate
limit
papercode
Here all fields are mandatory, suppose any one of the field is empty means I have to return like clgID should not be empty OR empID should not be empty, as per my knowledge I written the code I had posted here, but I think my logic is not correct. I hope we have to do combination logic but I don't know how to write this logic in PHP. Please any one update my code
My code:
//Test Case : 1
$case1['testCase'] = 'Checking empty condition for all fields';
$case1['clgID'] = '';
$case1['empID'] = '';
$case1['startDate'] = '';
$case1['limit'] = '';
$case1['papercode'] = '';
foreach($mainArray as $key => $val){
$input['clgID'] = $val['clgID'];
$input['empID'] = $val['empID'];
$input['startDate'] = $val['startDate'];
$input['limit'] = $val['limit'];
$input['papercode'] = $val['papercode'];
// $response = GetResponse($API_URL.'resultTrail', $input);
if($val['clgID'] != '' && $val['empID'] != '' && $val['startDate'] != '' && $val['limit'] != '' && $val['papercode'] != '' )
{
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] = 'c001';
$result[$key]['devTeamResult'] = 'success';
$result[$key]['testingTeamResult'] ='test case success';
}else
{
if($val['clgID'] == '' && $val['empID'] == '' && $val['startDate'] == '' && $val['limit'] == '' && $val['papercode'] == '' ){ // Checking empty condition for all fields
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case failure';
$result[$key]['data'] = 'All fields mandatory';
}else{
if($val['clgID'] == '' ){ // Checking empty condition for clgID
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case success';
$result[$key]['data'] ='clgID should not be empty';
}else{
if($val['empID'] == '' ){ // Checking empty condition for empID
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case success';
$result[$key]['data'] = 'empID should not be empty';
}else{
if($val['startDate'] == '' ){ // Checking empty condition for startDate
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case success';
$result[$key]['data'] = 'startDate should not be empty';
}
}
}
}
}
}
print_r($result);
Do you really want to be writing out that much code? What happens if you have to add another mandatory field?
Instead, be more generic.
$requiredFields = ["groupID", "studentID", "startFrom", "limit", "worksheetID"];
foreach($requiredFields as $key) {
if( empty($input[$key])) {
return $key." is required"; // or whatever error message
}
}
// if you get this far, ie. without hitting the "return", then all inputs are present.
// process the data now.
You can use this pattern for each input field:
$var = isset($_POST['field']) ? $_POST['field'] : '';
// Trim any trailing whitespaces
$conditionsOk = true;
if(trim($var) === '')
{
// Empty input
$conditionsOk = false;
}
if($conditionsOk) { // Perform action: db update, email... }
Let's take this opportunity to firstly, fix the issue to check if it's empty.
In php the isset() function checks if the index is in the array, and if it's empty.
Secondly, let's go over the code and clean it up a bit; please review the changes; clean code is the most important factor in being a successful developer.
else {
if (condition) {
}
}
Re-written to:
else if (condition) {
}
That's one of the issues with the code, the second issue is the cleanliness of the code; always try to keep the nested if statements to a minimum and move functionality to functions to keep the code readable and clean. - code that is not readable or maintainable doesn't carry any value.
I would go for a mapping and use a dynamic function.
Example mapping:
$fieldsMapping = [
"field" => exampleValidationFunction(),
"field2" => ["required" => True],
]
In return you can have flexibility and easily maintain the code albeit the learning curve.
The function to go over the mapping can be as follows:
function runTestCases() {
foreach ($fieldsMapping as $field => $validationRules) {
// your code here - check if its a function.. call function.. etc..
}
}

Simplify a long IF statement in PHP

Is there any simpler format for the following if statement below?
if((!empty($_SESSION['email'])) && (!empty($_SESSION['serial'])) && (!empty($_SESSION['name'])) && (!empty($_SESSION['number'])) && (!empty($_SESSION['institution'])) && (!empty($_SESSION['address'])) && (!empty($_SESSION['item2']))){
echo "OK u can proceed";
} else {
echo "U didn't complete the requested info";
}
Sorry if this is too simple for you, but really appreciate any pro suggestion.
Because conditional statement will "short circuit" on the first failure, re-writing your process using an iterator will be less performant.
If you only want to provide generalized feedback to the user, use your current method without the surplus parentheticals.
if(!empty($_SESSION['email']) &&
!empty($_SESSION['serial']) &&
!empty($_SESSION['name']) &&
!empty($_SESSION['number']) &&
!empty($_SESSION['institution']) &&
!empty($_SESSION['address']) &&
!empty($_SESSION['item2'])){
// valid
}
Alternatively (same same):
if(empty($_SESSION['email']) ||
empty($_SESSION['serial']) ||
empty($_SESSION['name']) ||
empty($_SESSION['number']) |
empty($_SESSION['institution']) ||
empty($_SESSION['address']) ||
empty($_SESSION['item2'])){
// invalid
}
Only if you wish to specify the cause of the invalidation should you bother to set up an iterative process. Furthermore, if you are going to perform iterations to validate, you can take the opportunity to remove any unwanted elements from the $_SESSION array that evil-doers may have injected to take advantage of any future loops on the superglobal.
$valid_keys=['email','serial','name','number','institution','address','item2'];
$validated=true; // default value
foreach($valid_keys as $key){
if(!empty($_SESSION[$key])){
$session_data[$key]=$_SESSION[$key];
}else{
echo "Oops, there was missing data on $key";
$validated=false;
break;
}
}
if($validated){...
// from this point, you can confidently run loops on `$session_data` or slap it directly into a pdo call knowing that it has been validated and ordered.
All that said, if there is even the slightest chance that your $_SESSION elements could hold zero-ish/false-y/empty values, then isset() is the better call (only NULL will get caught). Another good thing about isset() is that it allows multiple variables to be written into the single call and maintains the same/intended performance.
if(isset($_SESSION['email'],$_SESSION['serial'],$_SESSION['name'],$_SESSION['number'],$_SESSION['institution'],$_SESSION['address'],$_SESSION['item2'])){
// valid
}
or
if(!isset($_SESSION['email'],$_SESSION['serial'],$_SESSION['name'],$_SESSION['number'],$_SESSION['institution'],$_SESSION['address'],$_SESSION['item2'])){
// invalid
}
You could build a function where you pass all the keys you want to check.
I've changed $_SESSION to $SESSION to cheat the array with some values ...
<?php
$SESSION = [
'email' => 'xx',
'serial' => 'xx',
'name' => 'xx',
'number' => 'xx',
'institution' => 'xx',
'address' => 'xx',
'item2' => 'xx'
];
$keys = [
'email',
'serial',
'name',
'number',
'institution',
'address',
'item2'
];
if(isNotEmpty($SESSION, $keys)) {
echo "OK u can proceed";
} else {
echo "U didn't complete the requested info";
}
function isNotEmpty($array, $keys) {
foreach($keys as $key) {
if(empty($array[$key])) {
return false;
}
}
return true;
}
PHP Fiddle
Just "mind games"
$arr = array_flip('email', 'serial', 'name','number'...);
if (count(array_filter(array_intersect_key($_SESSION, $arr))) == count($arr)) {
This is just my opinion, but I think your expression is fine. Maybe you could format it in another way to make it more readable:
if ( !empty($_SESSION['email']) &&
!empty($_SESSION['serial']) &&
!empty($_SESSION['name']) &&
!empty($_SESSION['number']) &&
!empty($_SESSION['institution']) &&
!empty($_SESSION['address']) &&
!empty($_SESSION['item2']) ) {
/* Proceed */
} else {
/* Don't proceed */
}
Or maybe use a custom validation function:
/* My original version */
function filled_required_fields($fields, $array) {
$valid = true;
foreach ($fields as $field) {
$valid = $valid && !empty($array[$field]);
if (!$valid) return false;
}
return $valid;
}
/* Cleaner solution based on #caramba's answer */
function filled_required_fields($fields, $array) {
foreach ($fields as $field) {
if (empty($array[$field])) return false;
}
return true;
}
if (filled_required_fields(['email', 'serial', 'name', 'number', 'institution', 'address', 'item2'], $_SESSION) {
/* Proceed */
} else {
/* Don't proceed */
}

Nesting if else statements in PHP to validate a URL

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 => ""
);

Is this the proper use of an array and isset?

So I've got this code and part of it is a form, and ALL fields are absolutely required.
I just can't find clear documentation for my needs to validate everything.
would I do something like this?
$foo = $_POST['foo'];
$bar = $_POST['bar'];
$lorem = $_POST['lorem'];
$ipsum = $_POST['ipsum'];
$isSet = array($foo, $bar, $lorem, $ipsum);
if(isset($isSet)) { /* Do the stuff */ }
or is there a better way? I don't really want to do
if(isset($foo) && isset($bar) && isset($lorem)........
because i've got about 12 fields that are required
You can do:
if (isset($foo, $bar, $lorem, $ipsum)) {.....}
Saves you one step.
http://php.net/manual/en/function.isset.php
Remember that isset will return true if you have an empty string. So, technically
isset($_POST['foo'])
would return true if foo is passed in with a blank value:
foo=&bar=&...etc.
Also,
isset(array())
returns true;
If "" is not a valid value for one of those variables, you will want to do the following:
$requiredFields = array('foo', 'bar', 'lorem', 'ipsum');
$allValid = true;
foreach ($requireFields => $fieldName) {
if (isset($_POST[$fieldName]) && $_POST[$fieldName] != "") {
$allValid = $allValid && true;
} else {
$allValid = $allValid && false;
}
}
if ($allValid) {
//...success...
} else {
//...failed...
}
You essentially check that the variable was passed and also that the variable is not set to "".
Hope that helps.

I need a more efficient way of checking if multiple $_POST parameters isset

I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}

Categories