PHP check if array values are set - php

I've got the following function:
public function insertMember($username, $password, $fname, $lname)
{
$param = array();
$param['username'] = $username;
$param['password'] = $password;
$param['fname'] = $fname;
$param['lname'] = $lname;
return (count(array_filter($param, 'strlen')) == 0) ? FALSE : $this->insertIntoDB($param);
}
Is using (count(array_filter($param, 'strlen')) == 0) the right/best way to go about checking if all the variables $username, $password, $fname, $lname have been passed to the function?
Thanks,
Pav

if(count(array_filter($array)) == 0)
// all values are empty

You can't really check whether the variables have been passed to the function or not, you can only check their value. If the value is falsey, you may reject it. That doesn't necessarily mean that the variable wasn't passed, just that the value was falsey.
if (!$username || !$password || !$fname || !$lname)
To restrict it a bit more and accept, for example, empty strings and 0 as valid values, do something like:
public function insertMember($username = null, $password = null, $fname = null, $lname = null) {
if ($username === null || $password === null || $fname === null || $lname === null)
The best way may be to accept an array, which you can explicitly test for the existence of keys, regardless of their values:
public function insertMember($values) {
if (array_diff_key(array_flip(array('username', 'password', 'fname', 'lname')), $values)) {
// not all keys were set!
}
Regardless, this:
$param = array();
$param['username'] = $username;
$param['password'] = $password;
$param['fname'] = $fname;
$param['lname'] = $lname;
can be shortened to:
$params = compact('username', 'password', 'fname', 'lname');

Maybe right but not best.
If you need to check all variables:
if (empty($username) || empty($password) || empty($fname) || empty($lname)) return false;

You can omit the 'strlen' parameter, the default behavior of array_filter will work fine in this case. This way the code is just a tad shorter.
However, as a matter of style you may want to consider the explicit
if (empty($username) || empty($password) || ...)
because it more readily communicates to the reader what the requirements of the function are as regards its arguments.

Why not put your check even early? Make it something like that:
public function insertMember($username, $password, $fname, $lname) {
if (!$username || !$password || !$fname || !lname) {
return false;
} else {
$param = array();
$param['username'] = $username;
$param['password'] = $password;
$param['fname'] = $fname;
$param['lname'] = $lname;
return $this->insertIntoDB($param);
}
}

This won't check the validity of the data but:
// Do something if 4 (all) arguments were passed in
if(func_num_args() == 4) {
}

I prefer not using array_filter since it feels kind of dirty to pass a function in by its name. Although if you're using stdlib functions it may be okay.
I would use a loop
foreach ($param as $v) {
if (empty($v)) return false;
}

Related

Using empty() to adjust output with multiple variables

I have two primary variables that are composed of strings and other variables. I want the two primary variables only to be echo'ed if all the variables that they are comprised of have data.
The two primary variables are $introduction and colortxt.
$introduction is comprised of $finalvehicle3, $bodystyle, $mileage, and $hi.
$colortxt is comprised of $model, $exterior, and $interiorspec.
If any of the secondary variables are empty, I don't want the primary variable to be displayed.
Below is the code I have created that doesn't seem to be working. I have been using empty().
My PHP:
<?php
$finalvehicle3 = "Toyota Camry";
$bodystyle = "sedan";
$mileage = "30,000";
$hi = null;
$model = "Camry";
$exterior = "red";
$interiorspec = "black cloth";
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
echo "<textarea name='' id='' style='width: 565px;' rows='8' cols='60'>";
echo $introduction." ".$colortxt;
echo "</textarea>";
echo "<br><br>";
?>
In this case $introduction should not be displayed as $hi = null
I can't get empty([$finalvehicle3, $bodystyle, $mileage, $hi]) to work.
I was able to use:
if (empty($hi)
|| empty($finalvehicle3)
|| empty($bodystyle)
|| empty($mileage)){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle."
with ".$mileage." miles.";
}
Will that not work?
Check if both variables are not empty echo them out:
if (!empty($introduction) && !empty($colortxt)) {
echo $introduction." ".$colortxt;
}
As a side, while coding style has personal preference, where you set these variables seems awkward as you set them to empty based on a condition, but logically (my logical at least) is to instead preset them to empty and add data if the data exists.
INSTEAD of your code here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Do this:
$introduction = "";
$colortxt = "";
if (!empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true) {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (!empty([$model, $exterior, $interiorspec]) == true) {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Just looks cleaner to me :)
I'd also not create a new array to check multiple variables, and would do:
if (
!empty($finalvehicle3)
&& !empty($bodystyle)
&& !empty($mileage
&& !empty($hi)
) {
To clarify (not intended to take away from the other answers); only isset() can accept multiple comma-separated values, and not empty().
The manuals state:
on empty():
bool empty ( mixed $var )
on isset()
bool isset ( mixed $var [, mixed $... ] )
Therefore you need to separate and check if each value is empty.
I.e.:
if(empty($var1)) && empty($var2)){}
Or using the || (OR) logical operator depending on what you want to check for; if any or all are empty.
http://php.net/manual/en/language.operators.logical.php
Note:
What you used here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true)
theoretically would be a "false positive".
If anything, you will need to use the == true in a separate statement.
I.e.:
if(empty($var1)) && empty($var2) && $x_var == true){}
However, the first 2 would need the ! negation operator since you're checking if something is true.
I.e.:
if(!empty($var1)) && !empty($var2) && $x_var == true){}

How to check xml object is empty or not in php

if ($xml) {
$emailId = $xml->mail->id;
$mailPassword = $xml->mail->password;
if (!empty($emailId) && !empty($mailPassword)) {
$data['emailIdandPasswordCheck'] = 0;
}
}
this is a condition in which we are checking the values are empty or not but it is not working
in this id is empty and password is not empty.
but everytime xml object is coming in both id and password
because of this both the things are coming as non empty.
what check i can use to check xml object is empty or not?
You can use cast an array and you check the condition
$emailId = (array)$emailId;
$mailPassword = (array)$mailPassword;
if (!empty($emailId) && !empty($mailPassword) ){
}
OR
$emailId = (array)$emailId;
$mailPassword = (array)$mailPassword;
if (count($emailId)==0 && count($mailPassword)==0 ){
}
I think you want this:
if ($xml) {
$emailId = $xml->mail->id;
$mailPassword = $xml->mail->password;
if ( $emailId !=null && $emailId !="" && $mailPassword!=null && $mailPassword!="" ) {
$data['emailIdandPasswordCheck'] = 0;
}
}
Use isset() instead of empty()
if (!isset($emailId) && !isset($mailPassword)) {
$data['emailIdandPasswordCheck'] = 0;
}
OK. Here is what your code is doing.
$emailId = $xml->mail->id;
This sets null in $emailId if there is no value.
$mailPassword = $xml->mail->password;
And this sets null in $mailPassword if there is no value.
And your condition says
if emailId is non-empty and mailPassword is non-empty
And using empty always tells the conditions are true. Because empty returns true on null.
So instead using isset will solve the issue.
You can see the comparison table for further info.

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.

make an ifnot statement and if statement in one line

I'm trying to make an if statement with 2 conditions. One that checks if one variable is NOT present & does NOT matches the word "good2go" and the other that checks to make sure "body" variable is present. I'm trying to trip the error message here. Here is what I have and what I've tried, and none of it seems to work.
if (stripos($_POST['check'], 'good2go') == FALSE && $_POST['body']) {
$error = true; }
if (!$_POST['check'] == 'good2go' && $_POST['body']) {
$error = true; }
if (!stripos($_POST['check'], 'good2go') && $_POST['body']) {
$error = true; }
if ((!stripos($_POST['check'], 'good2go')) && $_POST['body']) {
$error = true; }
How do I get this to work?
here's the entire code of contact_us.php this has the validation code and the email code.
$error = false;
if (isset($_GET['action']) && ($_GET['action'] == 'send')) {
// Winnie the pooh check
//$t = tep_db_prepare_input($_POST['verify']);
if (!isset($_POST['check']) && !$_POST['check']=='good2go' && isset($_POST['body'])) {
$error = true;
} else { // Winnie the pooh Check
$name = tep_db_prepare_input($_POST['name']);
$email_address = tep_db_prepare_input($_POST['email']);
//IP recorder start
$ipaddress = $_SERVER["REMOTE_ADDR"];
$ip = "\n\nIP: " . $ipaddress;
$content = "\n\nName: ".$name."\n\nComments: ".$_POST['enquiry'];
$product = tep_db_prepare_input($_POST['product']);
if ($product) {
$product_text = "\n\nProduct Interest: ".$product; }
$content_ip = $content . $product_text. $ip;
$enquiry = tep_db_prepare_input($content_ip);
//IP recorder end
}
// BOF: Remove blank emails
// if (tep_validate_email($email_address)) {
// tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
// tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// } else {
// $error = true;
// $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
if (! tep_validate_email($email_address)) {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
}
if ($enquiry == '') {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_CONTENT_CHECK_ERROR);
}
if ($error == false) {
tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// EOF: Remove blank emails
}
}
Solution to your updated problem:
if (!isset($_POST['check']) || !$_POST['check']=='good2go' || !isset($_POST['body'])) {
$error = true;
}
The reason for the pipes vs ampersands is that you want to throw an error if ANY of the fields has issue. Also, you want to check if body is NOT set vs IS set. Glad this worked out for you!
and the other that checks to make sure "body" variable is not present.
if(stripos($_POST['check'], "good2go") !== false && !isset($_POST['body'])){
//code here
}
According to PHP docs regarding the stripos function:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So you need to change the first line to:
// Doing stripos checks you MUST use === (not ==)
if (stripos($_POST['check'], 'good2go') !== FALSE && $_POST['body']) {
$error = true; }
And to check if there is no $_POST['body'] you can change the above to:
if (stripos($_POST['check'], 'good2go') !== FALSE && (!isset($_POST['body'])) {
-- Update --
According to your comment, you need $_POST['check'] to equal 'good2go', then you shouldn't be using stripos as it will check for the existence of good2go regardless if it's exactly equal, or part of a string; 'wow this hamburger is good2go'.
So I would change the conditional to:
if (((isset($_POST['body'])) && (strlen($_POST['body']) > 0)) && ((!isset($_POST['check'])) || ($_POST['check'] !== 'good2go'))) {
// Post body has a value and Post check DOES NOT equal good2go, someone is hax0rin!
}
You may want to read up on Cross-site request forgery as it seems right inline with what you are working on.
One that checks if one variable is present & matches the word "good2go"
isset($_POST['check']) AND $_POST['check'] == 'good2go'
and the other that checks to make sure "body" variable is not present.
!isset($_POST['body'])
so, just put them together
if (isset($_POST['check']) AND $_POST['check'] == 'good2go' AND !isset($_POST['body'])) {
$error = true;
}
try this:
if(!empty($_POST['check']) && $_POST['check']=='good2go' && empty($_POST['body'])) { $error=true; }
Consider using empty instead of isset if your $_POST['body'] can be present with an empty value.
No need for all those unneeded functions. What you are trying to achieve is:
if (isset($_POST['check']) && $_POST['check']=='good2go' && !isset($_POST['body']) {
// your code
}
However, As per the title of the question: Use a ternary statement. Syntax is as such
$var = <condition> ? <true> : <false>;

What would you change in my code for best practices/maintenance?

I've got a small snippet of code below and I was curious what types of things you would change with regards to best practices/code maintainablity and so on.
function _setAccountStatus($Username, $AccountStatus)
{
if ($Username == '' || ($AccountStatus != 'Active' || $AccountStatus != 'Banned' || $AccountStatus != 'Suspended')) {
// TODO: throw error here.
}
$c1 = new Criteria();
$c1->add(UsersPeer::USERNAME,$Username);
$rs = UsersPeer::doSelect($c1);
if (count($rs) > 0) {
$UserRow = array_pop($rs);
$UserRow->setAccountStatus($AccountStatus);
try {
$UserRow->save();
} catch ( PropelException $e ) {
return false;
}
return true;
}
return false;
}
I would use the empty() instead of $Username == '' in your if statement. I haven't used propel before, but I would prefer to have this method be on my User object itself with the fetching and saving of the user object performed by a seperate object. Pseudo code would be something like this.
$user = userManager->getUser($username);
$user->setAccountStatus($accountStatus);
$userManager->saveUser($user);
An else clause before the last return false would be prefererred, just to make the code more readable.

Categories