Shorthand to check value in array - php

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.

Related

shortening this snippet of php and jquery, can it be done?

so I have a URL containing an array. When the page refreshes, I want to check if certain values are still present in the URL and if not, delete any cookies that may have been associated with it.
The code is as follows:
<?php if((isset($_GET['categories']) && !in_array(2, $_GET['categories']))) { ?>
if($.cookie('hf')=='1'){$.removeCookie('hf');}
<?php } if((isset($_GET['categories']) && !in_array(7, $_GET['categories']))) { ?>
if($.cookie('hb')=='1'){$.removeCookie('hb');}
<?php } if((isset($_GET['categories']) && !in_array(5, $_GET['categories']))) { ?>
if($.cookie('hp')=='1'){$.removeCookie('hp');}
<?php } if((isset($_GET['categories']) && !in_array(4, $_GET['categories']))) { ?>
if($.cookie('hw')=='1'){$.removeCookie('hw');}
<?php } ?>
This works perfectly, but is it the best way to go about checking the array and clearing any eventual cookies?
Any help or confirmation is appreciated. Thanks.
This should do it:
<?php
if(isset($_GET['categories']))
{
foreach(array(2 => 'hf', 4 => 'hw', 5 => 'hp', 7 => 'hb') as $key => $value)
{
if(!in_array($key, $_GET['categories']))
{
echo 'if($.cookie(\''.$value.'\')==\'1\'){$.removeCookie(\''.$value.'\');}';
}
}
}
?>
That's not shorter, but cleaner.
Not necessarily more readable (but could be readable if you rename function and arguments), but this is shorter and should work.
<?php function x($a,$b) {if((isset($_GET['categories']) && !in_array($a, $_GET['categories']))) { echo "if($.cookie('".$b."')=='1'){$.removeCookie('".$b."');";}
x(2,'hf');
x(7,'hb');
x(5,'hp');
x(4,'hw'); ?>
I find this solution simple and also easy to extend in the future:
$a = array("hf" => 2, "hb" => 7, "hp" => 5, "hw" => 4);
$b = filter_input(INPUT_GET, 'categories', FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY);
if ($b) {
$keys = array_keys(array_diff($a, $b));
foreach ($keys as $val) {
echo 'if($.cookie("' . $val . '")=="1"){$.removeCookie("' . $val . '");};';
}
}
Hope it helps.

Condition statement in value attr CGridView Yii

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)

How to quickly check what variables exist from a bunch of vars?

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;
}
}

how to use switch case?

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.

PHP if statement - select two different get variables?

Below is my example script:
<li><a <?php if ($_GET['page']=='photos' && $_GET['view']!=="projects"||!=="forsale") { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos\""); } ?>>Photos</a></li>
<li><a <?php if ($_GET['view']=='projects') { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos&view=projects\""); } ?>>Projects</a></li>
<li><a <?php if ($_GET['view']=='forsale') { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos&view=forsale\""); } ?>>For Sale</a></li>
I want the PHP to echo the "href="#" class="active" only when it is not on the two pages:
?page=photos&view=forsale
or
?page=photos&view=projects
I've also tried this and it doesnt work:
<li><a <?php if ($_GET['page']=='photos' && ($_GET['view']!=='projects' || $_GET['view']!=='forsale')) { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos\""); } ?>>Photos</a></li>
You can't do:
if ($var !== 'a' || !== 'b') ...
You have to do:
if ($var !== 'a' || $var !== 'b') ...
If you want to clean that code up I would suggest:
function active_view($content, $url, $view) {
if ($_GET['view'] == $view) {
return link($content, '#', 'active');
} else {
return link($content, $url);
}
}
function active_page_view() {
$args = func_get_args();
$content = array_shift($args);
$url = array_shift($args);
$page = array_shift($args);
if ($_GET['page'] == $page && !in_array($view, $args)) {
return link($content, '#', 'active');
} else {
return link($content, $url);
}
}
function link($content, $href, $class) {
$ret = '<a href="' . $href . '"';
if ($class) {
$ret .= ' class="' . $class . '"';
}
$ret .= '>' . $content . '</a>';
return $ret;
}
and then your code becomes:
<li><?php echo active_page_view('Photos', '/?page=photos', 'photos', 'projects', 'forsale'); ?></li>
<li><?php echo active_view('Projects', '/?page=photos&view=projects', 'projects'); ?></li>
<li><?php echo active_view('For Sale', '/?page=photos&view=forsale', 'project'); ?></li>
The above is illustrative rather than being final and complete. The point I'm trying to get across is you want to get in the habit of using some kind of templating mechanism even if you don't use a templating library (eg Smarty). You rarely want to embed complex logic into what is basically a view. If you use a library of functions (or objects) to create your markup it gives you a lot of control to escape special characters, automatically put in attributes, validate what you're putting in or whatever.
In this example, you probably want to have a data structure that represents your site navigation into which you enter what the current page is and it compares it to all the entries when dynamically constructing the navigation and automatically manipulates the links.
In addition to the problem cletus pointed out you also have an issue with the precedence of the operators. && has a higher precedence than ||. Therefore
if (
$_GET['page']=='photos'
&& $_GET['view']!=="projects"
|| $_GET['view']!=="forsale"
)
is equivalent to
if (
( $_GET['page']=='photos' && $_GET['view']!=="projects" )
|| $_GET['view']!=="forsale"
)
But you obviously want
if (
$_GET['page']=='photos'
&& ( $_GET['view']!=="projects" || $_GET['view']!=="forsale" )
)
Maybe not for two alternatives but if you have more options you might want to consider using !in_array(). e.g.
if (
'photos'=$_GET['page']
&& !in_array($_GET['view'], array("projects","forsale"))
)
<?php $view = $_GET['view'];
if($_GET['page'] == 'photos' && ($view =='projects' || $view == 'forsale'))
{
echo '<li>Photos</li>';
}
else
{
echo '<li>Photos</li>';
} ?>
if( $_GET[ 'page' ] != "photos" && $_GET[ 'view' ] != "forsale") {
...
}
else if( $_GET[ 'page' ] != "photos" && $_GET[ 'view' ] != "projects") {
...
}

Categories