I have the following select list:
<form action="mail.php" method="POST">
<select name="foo" id="foo">
<option value="sales">Sales</option>
<option value="salesAssist">Sales Assist</option>
<option value="billing">Billing</option>
<option value="billingAssist">Billing Assist</option>
</select>
</form>
I need to route the $mailTo variable depending on which option they select, Sales and Sales Assist go to sales#email.com, while Billing and Billing Assist go to billing#email.com.
PHP pseudeo code!
<? php
$_POST['foo'] if inArray(sales, salesAssist) foo="sales#email.com";
else if inArray(billing, billingAssist) foo="billing#email.com";
mailTo="foo"
?>
I know there is nothing correct about the above, but you can see what I am trying to do, change a variable's value based on the selected value. I don't want to do this with JavaScript, I would rather learn more PHP here.
Your pseudocode is pretty much right on. Here is an implementation, using in_array():
if (in_array($_POST['foo'], array('sales', 'salesAssit')) {
$foo = 'sales#email.com';
}
elseif (in_array($_POST['foo'], array('billing', 'billingAssit')) {
$foo = 'billing#email.com';
}
Of course, there are other ways to go about this. With only two values to search for, you could also do something like this:
if ($_POST['foo'] == 'sales' || $_POST['foo'] == 'salesAssit') {
$foo = 'sales#email.com';
}
elseif ($_POST['foo'] == 'billing' || $_POST['foo'] == 'billingAssit') {
$foo = 'billing#email.com';
}
Or, just check for the occurrence of the 'billing' or 'sales', using strpos():
if (strpos($_POST['foo'], 'sales') !== false) {
$foo = 'sales#email.com';
}
elseif (strpos($_POST['foo'], 'billing') !== false) {
$foo = 'billing#email.com';
}
However, what I like to do in situations like these, where you know it will always be one option or the other, is assign one as the default, and only change it if necessary:
$foo = 'sales#email.com';
if (strpos($_POST['foo'], 'billing') !== false) {
$foo = 'billing#email.com';
}
Try :
function startsWith($haystack, $needle) {
return $needle === "" || strpos($haystack, $needle) === 0;
}
if(startsWith($_POST["foo"], "sales") {
$foo = "sales#email.com";
} else if(startsWith($_POST["foo"], "billing") {
$foo = "billing#email.com";
}
Keep it simple, sir by using and array of e-mail values which you then cross check with array_key_exists.
// Set an array of e-mails.
$email_array = array();
$email_array['sales'] = "sales#email.com";
$email_array['salesAssist'] = "sales#email.com";
$email_array['billing'] = "billing#email.com";
$email_array['billingAssist'] = "billing#email.com";
// Do basic checks on 'foo'. If not? It's null.
$foo = isset($_POST['foo']) && !empty($_POST['foo']) ? $_POST['foo'] : null;
// Now check if 'foo' is in the array. If not? It's null.
$mailTo = !empty($foo) && array_key_exists($foo, $email_array) ? $email_array[$foo] : null;
The benefit of doing it this way is it’s clean & simple. You can set any e-mail you want in the array. And you can even set a default—instead of null—if you wish if somehow the script gets returned with none of the options selected.
Or if ternary logic seems confusing & you would rather just act on the data right away, this will work:
// Do basic checks on 'foo'. And check if 'foo' is in the array. If not? It's null.
$mailTo = null;
if ((isset($_POST['foo']) && !empty($_POST['foo'])) && array_key_exists($_POST['foo'], $email_array)) {
$mailTo = $email_array[$foo];
}
Related
Can Someone tell me what's wrong with this code
function someFunction($num=null) {
return $num;
}
if ($name = someFunction('mystr') && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
Why it is going in else condition and giving me notice of undefined variable $name
Edited: - if i do like this
if($name = someFunction() && $name ){
echo 'hello';
} else {
echo 'hi';
}
this time its also going on else condition as it should but it also not showing the error as i understand it, php just check my first condition $name = someFunction() and its fail then just else
but if i do as i do previously $name = someFunction('str') now $name is set so why notice of undefined variable
sorry for bad grammer
just want to know what is happening here.
It's because logical operators like && have higher precedence than the assignment operator =. You can read more about this here: http://php.net/manual/en/language.operators.precedence.php
The line
if ($name = someFunction('mystr') && $name ) {
is being evaluated like this:
if ($name = (someFunction('mystr') && $name) ) {
where the expression in the inner brackets is evaluated first. Because $name has not been defined before this point, a notice is raised.
I think what you're trying to do is this:
if (($name = someFunction('mystr')) && $name ) {
where you assign the value mystr to $name and then also evaluate that it's "truthy". But as pointed out in the comments, this is a bit of a strange approach. The following code would be equivalent:
$name = 'mystr';
if ($name) {
...
This feels a bit like a problem that's been cut down a bit too much in order to explain it, because it's not really clear why you're doing this.
you code output : hi becuase there is $name is in second is always null.
function someFunction($num=null) {
return $num;
}
$name = someFunction('mystr');
if ($name && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
output : mystr && mystr = 1 then output is hello
You haven't assigned anything to your variable $name and since it is an AND Condition, the first gets true but the second one doesn't so assign any value to your $name and add a condition for it to work.
In Javascript I would do something like this-
var time_array = [];
if ((previousTime > time_array[i]) || (time_array[i] === undefined) )
{
//Do Something
}
I want to do something similar in PHP
$time_array = array();
if (($previousTime> $time_array[$i]) || ($time_array[$i] === undefined) ))
{
//Do Something
}
I can do this very easily in Javascript , but I am a little confused about it in PHP.
$time_array = array();
if (!isset($time_array[$i]) || $previousTime > $time_array[$i])
{
//Do Something
}
It will first check if the variable is set and if it is not, the second condition will never be evaluated, so it's safe to use.
Edit: isset() checks whether a variable is declared and is set to a non-null value. You may want to use: if ($time_array[$i] === null) instead (that would be probably more similar to JS's undefined).
Just use this:
http://www.w3schools.com/php/func_array_key_exists.asp
if (array_key_exists($i,$time_array))
{
echo "Key exists!";
}
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.
What I'm doing is, if I haven't got an ID in either $_POST or $_SESSION then redirecting. Preference is given to $_POST. So I have this:
$bool = 0;
if (isset($_POST['id'])) {
$bool = 1;
} elseif (isset($_SESSION['id'])) {
$bool = 1;
}
if (!$bool) {
...//redirect
}
Is there a quicker way to write this, APART from just removing the braces?
if(!( isset($_POST['id']) || isset($_SESSION['id']) ))
redirect();
(not sure if I understand how what's given to $_POST is preference).
You could just do:
$has_id = isset($_POST['id']) || isset($_SESSION['id']);
if (!$has_id) {
// redirect
}
(I'd recommend you to give your variables more descriptive names than just $bool.)
Although if you aren't using the variable for anything else, you could just do:
if (!isset($_POST['id']) && !isset($_SESSION['id'])) {
// redirect
}
if (isset($_POST['id']) || isset($_SESSION['id'])) {
$bool = 1;
}
This will do it, simples
$bool = (isset($_POST['id']) || isset($_SESSION['id'])) ? 1 : 0; // if isset, 1
($bool == 1?header(Location: www.whatever.com):null;
Using Conditional Operator, you can achieve this in one line statement
Example:
c = (a == b) ? d : e;
How can I compare two variable strings, would it be like so:
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
And to check to see if a $_GET[] variable is present in the url would it be like this"
$myVars = $_GET['param'];
if ($myVars == NULL) {
//do code
}
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
$myVar = $_GET['param'];
if (isset($myVar)) {
//IF THE VARIABLE IS SET do code
}
if (!isset($myVar)) {
//IF THE VARIABLE IS NOT SET do code
}
For your reference, something that stomped me for days when first starting PHP:
$_GET["var1"] // these are set from the header location so www.site.com/?var1=something
$_POST["var1"] //these are sent by forms from other pages to the php page
For comparing strings I'd recommend using the triple equals operator over double equals.
// This evaluates to true (this can be a surprise if you really want 0)
if ("0" == false) {
// do stuff
}
// While this evaluates to false
if ("0" === false) {
// do stuff
}
For checking the $_GET variable I rather use array_key_exists, isset can return false if the key exists but the content is null
something like:
$_GET['param'] = null;
// This evaluates to false
if (isset($_GET['param'])) {
// do stuff
}
// While this evaluates to true
if (array_key_exits('param', $_GET)) {
// do stuff
}
When possible avoid doing assignments such as:
$myVar = $_GET['param'];
$_GET, is user dependant. So the expected key could be available or not. If the key is not available when you access it, a run-time notice will be triggered. This could fill your error log if notices are enabled, or spam your users in the worst case. Just do a simple array_key_exists to check $_GET before referencing the key on it.
if (array_key_exists('subject', $_GET) === true) {
$subject = $_GET['subject'];
} else {
// now you can report that the variable was not found
echo 'Please select a subject!';
// or simply set a default for it
$subject = 'unknown';
}
Sources:
http://ca.php.net/isset
http://ca.php.net/array_key_exists
http://php.net/manual/en/language.types.array.php
If you wanna check if a variable is set, use isset()
if (isset($_GET['param'])){
// your code
}
To compare a variable to a string, use this:
if ($myVar == 'hello') {
// do stuff
}
To see if a variable is set, use isset(), like this:
if (isset($_GET['param'])) {
// do stuff
}
All this information is listed on PHP's website under Operators
http://php.net/manual/en/language.operators.comparison.php