I want to add one If Statement in my script. If it gets any of the name mentioned, it converts it to admin. If script gets name like arsh, then it convert it to admin. But if script gets name like ARSH, Arsh, arSh, arsH then It should also convert it to admin... I can't manually define each work manually. So looking for a good way to get this work done.
if ($name=='arsh' || $name=='saif' || $name=='john' || $name=='smith'){
$name = 'Admin';
}
convert capital or small letters name to admin
You may compare the lowercase input name against lowercase literals:
$lname = strtolower($name);
if ($lname == 'arsh' || $lname == 'saif' || $lname == 'john' || $lname == 'smith') {
$name = 'Admin';
}
You can use strcasecmp() which doesn't require changing the case or mutating your variable:
if (strcasecmp($name, 'arsh') === 0 || strcasecmp($name, 'saif') === 0 || strcasecmp($name, 'john') === 0 || strcasecmp($name, 'smith') === 0){
$name = 'Admin';
}
Or just convert the names to either upper or lowercase before you do your comparison. Just make sure you assign it to another variable if you need to have the original value unaltered.
$name = strtolower($name);
if ($name=='arsh' || $name=='saif' || $name=='john' || $name=='smith'){
$name = 'Admin';
}
Related
I'm trying to create somewhat of a fuzzy search with PHP. Consider the following pseudo code/scenario below.
Take these $_POSTed values:
name
price
location
age
And I have an array of items (lets assume cars), of which each item contains the following properties:
name
price
location
age
So in my function, I use an if() within a foreach() to check if any of the posted data matches with an item and if it does, echo the item.
function search() {
$items = array(...);
$name = $_POST['name'];
$price = $_POST['price'];
$location = $_POST['location'];
$age = $_POST['age'];
foreach($items as $item) {
if(
$item['name'] == $name &&
$item['price'] == $price &&
$item['location'] == $location &&
$item['age'] == $age
){
echo json_encode($item);
}
}
}
The issue is that not every posted value is filled in, so for example $name could be empty i.e. $name = ''.
Question: How can I exclude any of the items in the if() statement if the initial $_posted key is empty without creating an if() inception type scenario? I considered using || but I'm pretty sure that wouldn't be the same as excluding a comparison all together. A
You can achieve that by taking advantage of PHP's lazy interpreter:
if(
(!$name || ($name && $item['name'] == $name)) &&
(!$price || ($price && $item['price'] == $price)) &&
(!$location || ($location && $item['location'] == $location)) &&
(!$age || ($age && $item['age'] == $age))
){
echo json_encode($item);
}
This will first check that each variable is not null, nor empty. (How exactly does if($variable) work?)
Also look at Does PHP have short-circuit evaluation?
I'm trying to run a check of my required fields where i use the empty function. Unfortunately empty considers 0 to be empty and my values could be 0 and one in the radio button. I've tried to use !is_int(myvalue) and yet it didn't work.
Here is my code:
<?php $required_fields = array('menu_name', 'position', 'visible');
foreach($required_fields as $fieldname) {
if(!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_int($_POST[$fieldname]))) {
$errors[] = $fieldname;
}
}
?>
It appears you want to test a string to see if it is an integer.
Try using is_numeric
http://www.php.net/manual/en/function.is-numeric.php
if(!isset($_POST[$fieldname]) // not in the post
|| (empty($_POST[$fieldname]) && 0 != $_POST[$fieldname]) // empty but not zero
|| (int) $_POST[$fieldname] == '')) // not an integer
) {
$errors[] = $fieldname;
}
I have a simple foreach statement grabbing all the fields from a submitted form. The fields are then put into a table that is sent via email. There are 3 fields that I need submitted and validated, but not sent with the email. Here is my script generating the table:
foreach($_POST as $name => $value) {
if($name !== "num1" || $name !== "num2" || $name !== "captcha") {
$text .= "<tr><td>$name</td><td>";
//if form field is array
if(is_array($value)) {
foreach($value as $symptom) {
$text .= $symptom . ", ";
}
//else no array
} else {
$text .= $value;
}
$text .= "</td></tr>";
}
}
Basically all form field names are set as $name and all values are set as $value. I am trying to include all fields except the ones named num1, num2, & captcha.
I am not redoing the way this form is handled, I just need to exclude these 3 fields from the table but my conditional statement isn't doing what I had expected. How can I ensure these three fields won't be included in the email?
change if($name !== "num1" || $name !== "num2" || $name !== "captcha")
to if($name !== "num1" && $name !== "num2" && $name !== "captcha")
Change the || in your if() to &&. Your if() as written will ALWAYS succeed, because whatever value you're testing will always "not be" any of those values at the same time.
PHP's continue will skip an interation of a loop, then you change to using == comparison operators... Try this:
if($name == "num1" || $name == "num2" || $name == "captcha")
continue;
else {
// rest of your code
}
You should use && instead of || in if statement.
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;
}
I am new to php and this little bugger has been eating up my day, perhaps it's due to some property of php I am unaware of?
As part of some code for getting some data out of an xml file (using the event based Expat parser), I have the following code
$xmlFields;
$fieldName = "";
............... some other code ............
function char($parser,$data)
{
global $xmlFields, $fieldName;
if($fieldName) {
if($fieldName == "brandName" || "oeNumber" || "articleId" || "quantityPerPackingUnit" || "attrName") {
$xmlFields[$fieldName] = $data;
echo $data;
}
}
}
I try to echo $xmlFields["brandName"] for example, and nothing is printed.
1) I know that $xmlFields["brandName"] is non-empty because echo $data actually returns something.
2) If I change to $xmlFields[$fieldName] = 'some string';
then echo $xmlFields["brandName"] will print 'some string'
so why won't it print $xmlFields["brandName"]?
Thanks in advance,
Yazan
You cannot link ORs like that.
try
if($fieldName == "brandName" || $fieldName =="oeNumber" || $fieldName =="articleId" || $fieldName =="quantityPerPackingUnit" || $fieldName == "attrName") {
As Deceze said a much better option when you are searching in an array is to use
if (in_array($fieldName, array("brandName", "oeNumber", "articleId", "quantityPerPackingUnit", "attrName")))
I know some languages allow such construct but php is not one of them.
The following expression
$fieldName == "brandName" || "oeNumber" || "articleId" || "quantityPerPackingUnit" || "attrName"
is parsed as
(
(
(
($fieldName == "brandName") || ("oeNumber")
) || ("articleId")
) || ("quantityPerPackingUnit")
) || ("attrName")
Notice that your equality check is separated from the other checks. In this case, the expression always evaluates to true.
You can use an array for this case:
in_array($fieldName, array("brandName", "oeNumber", "articleId", "quantityPerPackingUnit", "attrName"));
Try this as a shorter version of Iznogood's answer:
if (in_array($fieldName, array("brandName", "oeNumber", "articleId", "quantityPerPackingUnit", "attrName")))