how can i use following in code in switch case:
if($_GET['test']=='') { $test='demo';} else { $test=$_GET['test'];}
if($_GET['test1']=='') { $test1='demo';} else { $test1=$_GET['test1'];}
if($_GET['test2']=='') { $test2='demo';} else { $test2=$_GET['test2'];}
if($_GET['test3']=='') { $test3='demo';} else { $test3=$_GET['test3'];}
if($_GET['test4']=='') { $test4='demo';} else { $test4=$_GET['test4'];}
if($_GET['test5']=='') { $test5='demo';} else { $test5=$_GET['test5'];}
Thanx in advance
Why use a switch here? You can just use a simple foreach and create the variables using variable variables:
foreach (array('test', 'test1', 'test2', 'test3', 'test4', 'test5') as $var) {
$$var = isset($_GET[$var]) ? $_GET[$var] : '';
}
Alternatively, look into filter
You could always use a ternary operator ( http://www.tuxradar.com/practicalphp/3/12/4 )
$test = $_GET['test'] == '' ? 'demo' : $_GET['test'] ;
$test1 = $_GET['test1'] == '' ? 'demo' : $_GET['test1'] ;
.. etc ..
Although just iterating through repetitive variables could be done with a loop far easier.
Related
I want to declare a variable in a if statement and use it in the same statement. Is this simply not possible?
Example of problem (not actual use case though...):
if ($test = array('test'=>5) && $test['test'] === 5) {
echo 'test';
} else {
echo 'nope';
}
Error message:
NOTICE Undefined variable: test on line number 6
Because of Operator Precedence you will need to group the assignment with ():
if ( ($test = array('test'=>5)) && $test['test'] === 5) {
echo 'test';
} else {
echo 'nope';
}
A simple use case might be:
if ( ($parts = parse_url($url)) && $parts['port'] == 8080) {
// do stuff
}
when I do this in CgridView:
'value' => '$data->status == 1 ? "Payed" : "None" ',
it works, but when I do this:
'value' => 'if ($data->status == 1) { echo "Payed"; } else if($data->status == 2) { echo "Two"; } else { echo "None"; } '.
What I need to do to make work the second statement, or how I need to rewrite it?
Convert your statement to use ternary if:
'value' => '$data->status == 1 ? "Payed": ($data->status == 2 ? "Two" : "None")',
You could also use a function instead to give a bit more flexibility and make it more readable:
'value' => function($row, $data ) {
if ($data->status == 1) { return "Payed"; }
else if($data->status == 2) { return "Two"; }
else { return "None"; }
}
Just in case :
I've tried topher's solution and I found out that I had to switch param like that :
'value' => function($data, $row ) {
if ($data->status == 1) { return "Payed"; }
else if($data->status == 2) { return "Two"; }
else { return "None"; }
}
With topher's solution $data->attribute_name did not work and was, in fact, the row instead of the model..
Perhaps, if you don't need $row, don't pass it.
my solution:
function checkStatus($status)
{
if ($status == 1) {
return "opl";
} else if ($status == 2) {
return "nal";
} else {
return "neopl";
}
}
'value' => 'checkStatus($data->status)',
But your will work too) I will accept answer)
If you have 10 variables that are sometimes set, other times unset, is there a quick way to echo the ones that exist without throwing an exception? These vars come from user input.
I would currently write it as
if ($var_1 != NULL) { echo $var_1; }
if ($var_2 != NULL) { echo $var_2; }
if ($var_3 != NULL) { echo $var_3; }
if ($var_other_1 != NULL) { echo $var_other_1 ; }
if ($var_other_2 != NULL) { echo $var_other_2 ; }
etc.. But is there a more quicker way?
compact function will help you
Check this function: http://php.net/manual/en/function.get-defined-vars.php
You can do something like this:
<?php
$vararr = get_defined_vars();
foreach ($vararr as $name => $value) {
echo "{$name}: {$value}<br>\n";
}
Here's another option using variable variables and a list of the variables you want to examine:
foreach( array("var_1", "var_2") as $var )
{
if( isset($$var) )
{
echo $$var;
}
}
Is there a short way of doing this?
if ((isset($a['key']) && ($a['key'] == 'value')) {
echo 'equal';
// more code
}
else {
echo 'not equal';
// more code
}
I need to test lots of values on an array that can or cannot exist. I feel that this method is too verbose.
I could remove the isset() and mute the notices... but then I feel dirty.
Edit:
Answering Jack's question: "Could you give an example how you would test lots of values in an array?"
example:
if (isset($_GET['action']) && $_GET['action'] == 'view') {
//code
}
if (isset($_GET['filter']) && $_GET['filter'] == 'name') {
//code
}
if (isset($_GET['sort']) && $_GET['sort'] == 'up') {
//code
}
if (isset($_GET['tag']) && $_GET['tag'] == 'sometag') {
//code
}
etc...
For anyone still stumbling upon this question...
You could use PHP's coalescing operator:
if (($a['key'] ?? '') === 'value') {
echo 'equal';
// more code
}
else {
echo 'not equal';
// more code
}
See this question: using PHP's null coalescing operator on an array
I don't like to answer my own questions but I feel that the best and cleaner way to do this kind of checkings is to write a "helper funcion" like:
function iskeyval(&$a, $k, $v) {
return isset($a['key']) && ($a['key'] == 'value');
}
and then:
if (iskeyval($a, 'key', 'value')) {
...
}
else {
...
}
I have added comments to explain the code. Here is the code :
//this array maps the function with the get parameters
$functions = array (
"action" => "do_actions" ,
"filter" => "do_filters"
);
foreach ($_GET as $key=>$value) {
//check if this field is corresponding functions or not
if ( array_key_exists($key , $functions) ) {
call_user_func($functions[$key] , $key,$value);
}
}
function do_actions ($key , $value) {
//place your code here to play with this value
echo 'do_actions is called with ' . $key . 'and' . $value . "</br>";
}
function do_filters ($key , $value) {
//place your code here to play with this value
echo 'do_filters is called with ' . $key . ' and ' . $value . "</br>";
}
?>
$list = array(
0 => 'one',
1 => 'two',
2 => 'one',
3 => 'three',
4 => 'one',
);
if( #$list['xxx'] !== 'three')
echo 'Not ';
echo 'Equal';
Suppress the error reporting.
I'm looking for the best way how to use external variables in PHP with error level including E_NOTICE.
I have three possible ways, I would be happy, if you can give some hints on each or suggest a different approach that YOU like.
1.
class WebApp {
public static function _GET($Index) {
if (isset($_GET[$Index])) {
return $_GET[$Index];
} else {
return NULL;
}
}
}
// E_NOTICE, does not throw a notice:
echo WebApp::_GET('ID');
// E_NOTICE, throws a notice:
echo $_GET['ID'];
2.
class RequestSanitizer {
const V_INTEGER = 1;
const V_STRING = 2;
const V_REAL = 3;
public static function Sanitize($arr) {
foreach ($arr as $key => $val) {
if (array_key_exists($key, $_GET)) {
switch ($val) {
case RequestSanitizer::V_INTEGER:
$_GET[$key] = $_GET[$key] + 0;
break;
case RequestSanitizer::V_STRING:
$_GET[$key] = $_GET[$key] + '';
break;
case RequestSanitizer::V_REAL:
$_GET[$key] = $_GET[$key] + 0;
break;
}
} else {
$_GET[$key] = null;
}
}
}
}
RequestSanitizer::Sanitize(array(
'GraphID' => RequestSanitizer::V_INTEGER,
'UserName' => RequestSanitizer::V_STRING,
'Password' => RequestSanitizer::V_STRING,
'Price' => RequestSanitizer::V_REAL
));
echo $_GET['GraphID'];
3.
if (isset($_GET['ID']) && ($_GET['ID']+0>0)) {
echo $_GET['ID']
}
I would use
if (isset($_GET['ID']) && ($_GET['ID']+0>0)) {
echo (int)$_GET['ID']
}
with a casting to integer (int). If the value must be an integer.
i'd use a Request class that encapsulates all Php "superglobals" and provides methods like "param()", "numParam()", "arrayParam()" and so on.
$req = new Request();
$user_id = $req->numParam('id');
// user_id is guaranteed to be a valid integer or 0