Testing multiple values efficiently in PHP - php

Okay, so I have a few possible matches that I need to test. It can either equal A or B, so the obvious way to test it would be something like this:
if($val=="A"||$val="B"){
echo "yup";
}
I was just wondering if their were an easier way to test values without restating the variable for every value, like this (I know this doesn't work):
if($val==("A"||"B")){
echo "yuppers";
}
Is something like this possible?

You can use in_array
$array = array('A','B','other values');
if(in_array($val, $array)){
// value is in array
}else {
// invalid value
}

You can use in_array:
if (in_array($val, array('A', 'B'))) {
echo 'yuppest';
}

you can add "A" and "B" to the array and use in_array method but this is definitely not more efficient than $val=="A" || $val =="B"

Related

Is this the correct way of checking empty array?

I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.
you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>
if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.
Use empty:
if (empty($myArray)) {
...
}
Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>
It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}
<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}
It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.

PHP fastest way to iterate over list? [duplicate]

Okay, so I have a few possible matches that I need to test. It can either equal A or B, so the obvious way to test it would be something like this:
if($val=="A"||$val="B"){
echo "yup";
}
I was just wondering if their were an easier way to test values without restating the variable for every value, like this (I know this doesn't work):
if($val==("A"||"B")){
echo "yuppers";
}
Is something like this possible?
You can use in_array
$array = array('A','B','other values');
if(in_array($val, $array)){
// value is in array
}else {
// invalid value
}
You can use in_array:
if (in_array($val, array('A', 'B'))) {
echo 'yuppest';
}
you can add "A" and "B" to the array and use in_array method but this is definitely not more efficient than $val=="A" || $val =="B"

match a variable with at least one value in an array - php

I have one variable that comes from a database.
I then want to check whether that value is the same of one of the values in an array.
If the variable matches one of the array values, then I want to print nothing, and if the variable does not match one of the array values, then I want to print something.
This is the code I have been trying without luck, I know that contains is not valid code, but that is the bit I cannot find any info for:
<?php
$site = getStuff();
$codes = array('value2', 'value4');
if ($codes contains $site)
{
echo "";
}
else
{
echo "something";
?>
So if the database would return value1 for $site, then the code should print "something" because value1 is not in the array.
The function you are looking for is in_array.
if(in_array($site, array('value2', 'value4')))
if(!in_array($site,$codes)) {
echo "something";
}
To provide another use way to do what the other answers suggest you can use a ternary if
echo in_array($site, $codes)?"":"something";

Is there a better way of determining empty associative arrays in php 5.3?

The empty() function in php 5.3 does not work well for associative arrays. I have an associative array that could have some 30+ elements.
$arr = array(
'one'=>kwara,
'two'=>osun,
...
'thirty'=>lagos
)
If the associative array is empty like so:
$arr = array(
'one'=>'',
'two'=>'',
...
'thirty'=>''
)
and I need to check if the array is empty, the following will not work in php 5.3.
if(empty($arr))
{
echo "array is empty<br />>";
}
else
{
echo "array is NOT empty<br />";
}
and will return 'array is NOT empty'. I am aware that the behaviour is different in php 5.4 but my current platform is php 5.3.
To overcome this problem, I have used the following:
if(strlen(implode('',array_values($arr))) > 0)
{
echo "array is NOT empty<br />>";
}
else
{
echo "array is empty<br />";
}
The question is: is there a better of achieving this in php 5.3?
Short answer: No
Longer answer: The array you are looking at is not empty at all, it contains a bunch of keys with zero length strings. Your solution is probably one of the shortest possible and readable. You may want to wrap it in a function of your own though.
Have you tried:
if (sizeof(array_filter($array)) === 0) // do your stuff
Also you original could be improved like:
if (implode($array) !== '') // do your stuff
Empty will work only with really empty values, your array has keys assigned so its not empty. Your solution is probably best way to do what you want - its hard to say, you would need to make some benchmarks, it can be done in many other ways:
if (array_filter($arr) === array()) {}
// or
if (!implode('', $arr)) {}

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.

Categories