Validate object and assign it to something in one line - php

I am looking for an optimized way to do something like this:
Check if what am I receiving from a function:
Is set
Is an array
If so, I would like to directly assign it to a variable.
For that propose, I would do something like:
Let's suppose that I'm calling a function that returns me an array (or not).
<?php
$data_table = isset(Api::get($url)) && is_array(Api::get($url)) ? (array)Api::get($url) : array();
?>
However, doing something like this would require three calls to the function:
The first, to check in an if statement if it is really returning something
The second to check if the return is an array
The thing to assign the return to $data_table variable
I've thought about doing the following, but I'm not sure how it could work like this:
<?php
$data_table = isset($result = Api::get($url)) && is_array($result) ? (array)$result : array();
?>
Please let me know your thoughts.
Thanks.

You can use empty(). From the manual:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
It doesn't quite check for whether it's an array, rather whether the variable (of many types) is empty, but it's a shorter way than what you're doing. I think if you want to check for an array and for isset, that's what you'll have to do - no way around it.
<?php
$data_table = !empty($result) ? $result : array();
?>

Related

One PHP statement to use result of IF statement for assignment

I have a situation where I have a function that does some database retrieval and either returns a value or an error. I'd like to have a single statement that calls the function and depending on result either assigns the returned value or a default value.
Using the tenary operator I could do something like this:
$val=(getVal($param)!='error' ? getVal($param) : "default");
but I don't want to have to call getVal twice because it excutes database queries and is expensive on performance.
I could also do it in two statements, but if possible I just want one. Appreciate any help.
Try this
$val=(($result=getVal($param))!='error' ? $result : "default");
There are only two ways I am aware of (maybe there is more).
Either you first assign function result to a variable and then use if:
$res = getVal($param);
$val = ($res != 'error' ? $res : "default");
Note: This is possibly the best option both for readability and performance.
Or you modify function from this:
function getVal($param) {
...
return $something;
}
to this:
function getVal ($param, &$result) {
...
$result = $something;
return $something;
}
And use it:
$val = (getVal($param,$res) != 'error' ? $res : "default");
But this looks fishy to me

PHP take string and check if that string exists as a variable

I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>

Check if $var = anything in an array?

I need to be able to test if $post_count is equal to any number in a given array. Here is an example of what I am trying to achieve:
$posts_even = array(2,4,6,8,10);
$posts_odd = array(1,3,5,7,9);
$posts_ev3 = array(1,4,7,10);
$posts_ev4 = array(1,5,9);
--
$post_count=1;
$post_count=++; //in wordpress loop so each subsequent post is +1
--
if ($post_count= //any value in $posts_ev4) :
echo 'this'
else :
NULL;
endif;
I have been able to make this work using the or operator but I end up with very long blocks of code.....
if (($post_count=1) || ($post_count=2)) :
echo 'this'
else :
NULL;
endif;
I am guessing there is a simpler way to do this but I am new to PHP so I am not sure! Any help would be greatly appreciated.
Try:
if (in_array($post_count, $post_ev4)) {}
See: in_array()
Use in_array() to check if value exists in array.
if (in_array($post_count, $posts_ev4)) :
echo 'this'
else :
NULL;
endif;
Check out the isset() function in the PHP Manual.
There are array functions in php. Ypu can use "is_array" function to check whether its array or not. & to check for a value you can use "in_array" function.
if(is_array($array) && in_array($post_count,$array))
{
// do operation
}

PHP: testing for existence of a cell in a multidimensional array

I have an array with numerous dimensions, and I want to test for the existence of a cell.
The below cascaded approach, will be for sure a safe way to do it:
if (array_key_exists($arr, 'dim1Key'))
if (array_key_exists($arr['dim1Key'], 'dim2Key'))
if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))
echo "cell exists";
But is there a simpler way?
I'll go into more details about this:
Can I perform this check in one single statement?
Do I have to use array_key_exist or can I use something like isset? When do I use each and why?
isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like
isset($arr[1][2][3])
is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).
However, if you have
$arr['a'] = null;
then
isset($arr['a']); // false
array_key_exists('a', $arr); // true
comment followup:
Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:
isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.
I was having the same problem, except i needed it for some Drupal stuff. I also needed to check if objects contained items as well as arrays. Here's the code I made, its a recursive search that looks to see if objects contain the value as well as arrays. Thought someone might find it useful.
function recursiveIsset($variable, $checkArray, $i=0) {
$new_var = null;
if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable[$checkArray[$i]];
else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable->$checkArray[$i];
if(!isset($new_var))
return false;
else if(count($checkArray) > $i + 1)
return recursiveIsset($new_var, $checkArray, $i+1);
else
return $new_var;
}
Use: For instance
recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))
In my case in drupal this ment for me that the following variable existed
$variables['content']['body']['#object']->body['und']
due note that just because '#object' is called object does not mean that it is. My recursive search also would return true if this location existed
$variables->content->body['#object']->body['und']
For a fast one liner you can use has method from this array library:
Arr::has('dim1Key.dim2Key.dim3Key')
Big benefit is that you can use dot notation to specify array keys which makes things simpler and more elegant.
Also, this method will work as expected for null value because it internally uses array_key_exists.
If you want to check $arr['dim1Key']['dim2Key']['dim3Key'], to be safe you need to check if all arrays exist before dim3Key. Then you can use array_key_exists.
So yes, there is a simpler way using one single if statement like the following:
if (isset($arr['dim1Key']['dim2Key']) &&
array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...
I prefer creating a helper function like the following:
function my_isset_multi( $arr,$keys ){
foreach( $keys as $key ){
if( !isset( $arr[$key] ) ){
return false;
}
$arr = $arr[$key];
}
return $arr;
}
Then in my code, I first check the array using the function above, and if it doesn't return false, it will return the array itself.
Imagine you have this kind of array:
$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );
You can write something like this:
$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );
if( $arr ){
//You can use the variable $arr without problems
}
The function my_isset_multi will check for every level of the array, and if a key is not set, it will return false.

$_GET and isset()

I am getting tried of if isset($_GET['whatever'])... before the rest of my if statement. E_NOTICE errors are way to handy to turn off and for $_POST variables I have a solution in my init script..
$POST = (is_array( $_POST ) && count( $_POST ) > 0);
I find this helps self posting scripts look clean.
if ($POST) {
// now do something with $_POST...
}
I'm not sure how to dynamically do this if you have no idea what the key is? Can anyone help find a similar solution for $_GET variables?
EDIT:
I simply want if ($_GET['whatever'] == "whatever"); to return false if it's not set and no E_NOTICE errors.
EDIT:
Sorry if I'm unclear I'm looking for a solution for $_GET not $_POST--I only am using $_POST as an example of what I hope to achieve.
Sometimes I use a global GET function:
function GET($key, $default = null) {
return isset($_GET[$key]) ? $_GET[$key] : $default;
}
The main idea of all that mess is simple: every variable in your program should be initialized before use.
Thus, the best you can do is to set all variables centralized, say, at the very top of your script.
But there are some different cases. For the case you posted, you need none of these but
if ($_SERVER['REQUEST_METHOD'] == "POST")
Already answered, but since it wasn't mentioned, also try:
$var = filter_input(INPUT_GET, 'varname');
That will return null if it doesn't exist, without the annoying array notices, and also filters out potential bad stuff in various ways. See also: http://www.php.net/filter
You can make a function to do this for you.
function getVar($item){
return isset($_GET[$item]) ? $_GET[$item] : '';
}
Then you can do if(getVar('whatever') == "whatever").
Here are two methods.
/*
* Makes any request keys into variables of the same name
*/
foreach($_GET AS $key => $value) {
${$key} = ($value);
}
//Assuming a input key of $_GET['whatever']
echo $whatever;
/*
* Casting to an object
*/
$get = (object) $_GET;
//Assuming a input key of $_GET['whatever']
echo $get->whatever
A third option that I can think of is making the $_GET into its own class. PHP overloading is handy trick for doing this.
http://php.net/manual/en/language.oop5.overloading.php
I didn't feel like writing up an example demonstrating this. :)
simple I think you want to check if get value is set then need to do the next step otherwise do different
I like the first answer but need to check thats if it works for you
if(isset($_GET['whatever']){
if ($_GET['whatever'] == "whatever");{
//do the rest
}
else{
//do the rest
}
}
hope it may help if what I think is your need
short
no notice
$key = &$_POST['key'];
This way (inside function) it is depracted, and shows error:
function f($s){}
f(&$_POST['key']);
Fatal error: Call-time pass-by-reference has been removed
When writing these sorts of scripts, I usually do something like this at the top:
$submitted = isset($_POST['submit']) ? true : false;
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
(etc.)
Then, when testing the values, it looks something like this:
if ($submitted)
{
if ($username && $password)
{
// do stuff with username and password including testing their values
}
}
It seems to work pretty well for me.

Categories