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";
}
Related
I need to get index of from array of objects without using loop as per the key name using PHP. Here I am explaining my code below.
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
$key = array_search('Jack', $arr);
echo $key;exit;
Here my code does not give any output. By using some key name I need the index of that object present inside array and also I dont want to use any loop. I need Is ther any PHP in build method so that I can get the result directly.
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
function myfunction($v){return $v['name'];}
echo array_search('Jack', array_map( 'myfunction', $arr ));
<?php
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
//calling function searchByName
$key = searchByName('Jasck',$arr);
if($key != '-1'){
print_r($arr[$key]);
}else{
echo "No match found";
}
//function to chek if the name is there or not.
function searchByName($name, $array) {
foreach ($array as $key => $val) {
if ($val['name'] == $name) {
return $key;
}
}
return '-1';
}
sandbox
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";
}
The following foreach query is inserting only values in ['options']['Colors'] and not those in ['options']['Color'] ???
Updated Question:
if (!is_array($value['options']['Colors'])) {
$value['options']['Colors'] = array($value['options']['Colors']);
}
if (!is_array($value['options']['Color'])) {
$value['options']['Color'] = array($value['options']['Color']);
}
if(isset($value['options']['Colors'])) {
$colorArr = $value['options']['Colors'];
} else if(isset($value['options']['Color'])) {
$colorArr = $value['options']['Color'];
}
foreach ($colorArr as $colors) {
$stmt->execute(array(':pid' => $PID, ':colors' => $colors));
}
You can't do this as this way... it does not make a sense. what exactly do you want to do ?
if you want check the existence of a value in array you could use in_array function like this:
if(in_array("someValue", $someArray)) {
// Do something ...
}
We can not use OR in foreach loop. Instead we can use if statement to verify and then can go ahead like below:
if(isset($value['media']['options']['Colors'])) {
$colorArr = $value['media']['options']['Colors'];
} else if(isset($value['media']['options']['colors'])) {
$colorArr = $value['media']['options']['colors'];
}
foreach ($colorArr as $colors) {
// You can use $colors now where you want
}
If you really insist on having the array such that either key may be used, I suggest you convert all to lower case before using them
foreach($value['media']['options'] as &$key => $value){
if($key == 'Colors'){
$key = 'colors';
}
}
Then try using the array as before, but without the need for the OR statement checking for 'Colors'
you could merge the arrays then loop, be careful of key conflicts though. can one option have both a "color" and a "Color" in which case it can get messy really fast, which one do you use, the first, the second, both, none?
$colors = array_merge ($value['media']['options']['Colors'], $value['media']['options']['colors'] );
foreach($colors as $color ){
}
Without having to change the function signature, I'd like a PHP function to behave differently if given an associated array instead of a regular array.
Note: You can assume arrays are homogenous. E.g., array(1,2,"foo" => "bar") is not accepted and can be ignored.
function my_func(Array $foo){
if (…) {
echo "Found associated array";
}
else {
echo "Found regular array";
}
}
my_func(array("foo" => "bar", "hello" => "world"));
# => "Found associated array"
my_func(array(1,2,3,4));
# => "Found regular array"
Is this possible with PHP?
Just check the type of any key:
function is_associative(array $a) {
return is_string(key($a));
}
$a = array(1 => 0);
$a2 = array("a" => 0);
var_dump(is_associative($a)); //false
var_dump(is_associative($a2)); //true
You COULD use a check with array_values if your arrays are small and you don't care about the overhead (if they are large, this will be quite expensive as it requires copying the entire array just for the check, then disposing of it):
if ($array === array_values($array)) {}
If you care about memory, you could do:
function isAssociative(array $array) {
$c = count($array);
for ($i = 0; $i < $c; $i++) {
if (!isset($array[$i])) {
return true;
}
}
return false;
}
Note that this will be fairly slow, since it involves iteration, but it should be much more memory efficient since it doesn't require any copying of the array.
Edit: Considering your homogenious requirement, you can simply do this:
if (isset($array[0])) {
// Non-Associative
} else {
// Associative
}
But note that numerics are valid keys for an associative array. I assume you're talking about an associative array with string keys (which is what the above if will handle)...
Assuming $foo is homogeneous, just check the type of one key and that's it.
<?php
function my_func(array $foo) {
if (!is_int(key($foo))) {
echo 'Found associative array';
} else {
echo 'Found indexed array';
}
}
?>
In the light of your comment Assume arrays are homogenous; no mixtures.:
Just check if first (or last, or random) key is an integer or a string.
This would be one way of doing it, by checking if there's any keys consisting of non-numeric values:
function my_func($arr) {
$keys = array_keys($arr); // pull out all the keys into a new array
$non_numeric = preg_grep('/\D/', $keys); // find any keys containing non-digits
if (count($non_numeric) > 0) {
return TRUE; // at least one non-numeric key, so it's not a "straight" array
} else {
return FALSE: // all keys are numeric, so most likely a straight array
}
}
function is_associative($array) {
return count(array_keys($array)) != array_filter(array_keys($array), 'is_numeric');
}
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;
}