This is my array in PHP:
$arr['key1']='value1';
$arr['key2']='value2';
$arr['key3']='value3';
$arr['key4']='value4';
$arr['key5']='value5';
$arr['key6']='value6';
I would like to test if a key is in the array. Is this function the correct way to proceed?
function isKeyInArray($key, $arr) {
if(isset($arr[$key]))
return true;
else
return false;
}
What I expect is that:
isKeyInArray('key3', $arr) // return true
isKeyInArray('key9', $arr) // return false
Many thanks in advance.
You can use array_key_exists.
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
See http://php.net/manual/en/function.array-key-exists.php
Use array_key_exists
if(array_key_exists('key6',$arr))
echo "present";
else
echo "not present";
Using isset() is good if you consider that null is not a suitable value. Also isset is faster than array_key_exists.
$a = [ 'one' => 1, 'two' => null ];
isset($a['one']); // true
isset($a['two']); // false
array_key_exists('two', $a); // true
Use php function array_key_exists('key3', $a);
First google your need and only after that you can use your own function. This will save lots of your time.
Related
Is there any elegant way to check if
$review['passenger'] has any $review['passenger']['*']?
Try with is_array(). It will check if it is an array or not -
if(is_array($review['passenger'])) {
// is an array
}
Or if you want to check if some key is present or not then -
if(array_key_exists('key', $review['passenger'])) { ... }
I believe Danius was using "['*']" to reference "one or more sub-arrays", instead of specifying it as "the" sub-array.
About his question, the only way to verify if a specific KEY of your array has sub-arrays is checking its sub-items, one by one, to identify if any one of them is an array.
It may not be "elegant", but it is definitively functional:
function has_array($arr) {
$has_array = false;
foreach ($arr as $item):
if (is_array($item)):
$has_array = true;
break;
endif;
endforeach;
return $has_array;
}
Simply call the function this way:
$result = has_array($review['passenger']);
I hope it helps.
You can use array_key_exists:
$array = array(
"passenger" => array(
"*" => "ok"
)
);
if(array_key_exists('*', $array['passenger'])){
echo "ok";
} else {
echo "not ok";
}
I've got a function that is used in a loop, however it is not working at all, here's example of my code
function is_banned_category($a) {
if(!is_array($a)) {
echo "returning false <Br/>";
return false;
}
$banned_list = array(
'Shopping',
'Product Info'
);
foreach($a as $cat) {
if(array_search($cat,$banned_list)) {
$return = true;
} else {
echo "Not found in:'{$cat}' <br/>";
}
}
return $return;
}
$a = array('Shopping');
if(is_banned_category($a)) {
echo "Item will not be added as it's in banned category";
}
Which would produce:
Item will not be added as it's in banned category
Am I missing something obvious here? It works with "Product Info" but not "Shopping"?
array_search($cat,$banned_list) returns 0, witch causes expression to evaluate to false. use in_array() or evaluate using Identical Operator ===
array_search returns the key of array value if exist, so in your case
array key of Shopping is "0"
if(array_search($cat,$banned_list)) // return 0
So else part will be worked
The function array_search will return the index of the occurrence if found (which could be 0, which evaluates to false), or else false if not found, so you must use
if(array_search($cat, $banned_list) !== false) {
[.. do your stuff .. ]
}
to perform the check, or else you could do
if(in_array($cat, $banned_list)) {
[.. do your stuff .. ]
}
which, IMHO, is a little bit cleaner.
I have a question, how do I put a condition for a function that returns true or false, if I am sure that the array is empty, but isset() passed it.
$arr = array();
if (isset($arr)) {
return true;
} else {
return false;
}
In this form returns bool(true) and var_dump shows array (0) {}.
If it's an array, you can just use if or just the logical expression. An empty array evaluates to FALSE, any other array to TRUE (Demo):
$arr = array();
echo "The array is ", $arr ? 'full' : 'empty', ".\n";
Sometimes it is suggested instead of just if'ing the array variable like:
if (!$array) {
// empty
}
to write out:
if (empty($array)) {
// empty
}
for readability reasons. Compare empty(php) language construct.
The PHP manually nicely lists what is false and not.
Use PHP's empty() function. It returns true if there are no elements in the array.
http://php.net/manual/en/function.empty.php
Use empty() to check for empty arrays.
if (empty($arr)) {
// it's empty
} else {
// it's not empty
}
You can also check to see how many elements are in the array via the count function:
$arr = array();
if (count($arr) == 0) {
echo "The array is empty!\n";
} else {
echo "The array is not empty! It has " . count($arr) . " elements!\n";
}
use the empty property as
if (!empty($arr)) {
//do what u want if its not empty
} else {
//do what if its empty
}
I have an array
$data = array( 'a'=>'0', 'b'=>'0', 'c'=>'0', 'd'=>'0' );
I want to check if all array values are zero.
if( all array values are '0' ) {
echo "Got it";
} else {
echo "No";
}
Thanks
I suppose you could use array_filter() to get an array of all items that are non-zero ; and use empty() on that resulting array, to determine if it's empty or not.
For example, with your example array :
$data = array(
'a'=>'0',
'b'=>'0',
'c'=>'0',
'd'=>'0' );
Using the following portion of code :
$tmp = array_filter($data);
var_dump($tmp);
Would show you an empty array, containing no non-zero element :
array(0) {
}
And using something like this :
if (empty($tmp)) {
echo "All zeros!";
}
Would get you the following output :
All zeros!
On the other hand, with the following array :
$data = array(
'a'=>'0',
'b'=>'1',
'c'=>'0',
'd'=>'0' );
The $tmp array would contain :
array(1) {
["b"]=>
string(1) "1"
}
And, as such, would not be empty.
Note that not passing a callback as second parameter to array_filter() will work because (quoting) :
If no callback is supplied, all entries of input equal to FALSE (see
converting to boolean) will be removed.
How about:
// ditch the last argument to array_keys if you don't need strict equality
$allZeroes = count( $data ) == count( array_keys( $data, '0', true ) );
Use this:
$all_zero = true;
foreach($data as $value)
if($value != '0')
{
$all_zero = false;
break;
}
if($all_zero)
echo "Got it";
else
echo "No";
This is much faster (run time) than using array_filter as suggested in other answer.
you can loop the array and exit on the first non-zero value (loops until non-zero, so pretty fast, when a non-zero value is at the beginning of the array):
function allZeroes($arr) {
foreach($arr as $v) { if($v != 0) return false; }
return true;
}
or, use array_sum (loops complete array once):
function allZeroes($arr) {
return array_sum($arr) == 0;
}
#fireeyedboy had a very good point about summing: if negative values are involved, the result may very well be zero, even though the array consists of non-zero values
Another way:
if(array_fill(0,count($data),'0') === array_values($data)){
echo "All zeros";
}
Another quick solution might be:
if (intval(emplode('',$array))) {
// at least one non zero array item found
} else {
// all zeros
}
if (!array_filter($data)) {
// empty (all values are 0, NULL or FALSE)
}
else {
// not empty
}
I'm a bit late to the party, but how about this:
$testdata = array_flip($data);
if(count($testdata) == 1 and !empty($testdata[0])){
// must be all zeros
}
A similar trick uses array_unique().
You can use this function
function all_zeros($array){//true if all elements are zeros
$flag = true;
foreach($array as $a){
if($a != 0)
$flag = false;
}
return $flag;
}
You can use this one-liner: (Demo)
var_export(!(int)implode($array));
$array = [0, 0, 0, 0]; returns true
$array = [0, 0, 1, 0]; returns false
This is likely to perform very well because there is only one function call.
My solution uses no glue when imploding, then explicitly casts the generated string as an integer, then uses negation to evaluate 0 as true and non-zero as false. (Ordinarily, 0 evaluates as false and all other values evaluate to true.)
...but if I was doing this for work, I'd probably just use !array_filter($array)
how can i check if logo exists in this array called $attachements print_r is below:
Array (
[logo] => /home/richar2/public_html/ioagh/images/stories/jreviews/20100510115659_1_img.gif
)
when theres no logo, the array print_r's
Array ( )
i tried:
if (isset($attachments['logo']) ) {..}
but the conditional code runs when there is no logo
Use the function array_key_exists.
http://php.net/manual/en/function.array-key-exists.php
It's very stange that isset() is not working, I am pretty sure it should. Maybe you have a problem elsewhere in your code.
Anyway, if you want to try something else, there is a specific function: array_key_exists()
This works for me as expected:
$arr['logo'] = '/home/richar2/public_html/ioagh/images/stories/jreviews/20100510115659_1_img.gif';
print_r($arr);
if (isset($arr['logo'])){
echo $arr['logo'];
}else{
echo 'Key doesn\'t exist!';
}
Are you sure you set $arr['logo'] = null, not $arr['logo'] = ''?
For the latter you can also check
if (isset($arr['logo'] && !empty($arr['logo'])){
...
}
but the conditional code runs when
there is no logo
You could construct an else clause to take appropriate action:
if (isset($attachments['logo']))
{
// logo is set
}
else
{
// loto is not set
}
Or simply try this:
if (array_key_exists('logo', $attachments))
{
// logo is set
}
More info on array_key_exists
You can use array_key_exists.
you could write it like:
function md_array_key_exists ($key, $array)
{
foreach ($array as $item => $val)
{
if ($item === $key)
{
return true;
}
if (is_array ($val))
{
if (true == marray_key_exists ($key, $val))
return true;
}
}
return false;
}