PHP - elegant way to check if assoc array value has a subarray? - php

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

PHP array inside array and non-array access [duplicate]

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

How can we use a condition inside a foreach loop

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 ){
}

PHP If statements and Arrays

I have an array
$results = array(101, 102, 103, 104, 105)
I also have a input field where the user enters a number
<input type ="text" name="invoice" />
I put what the number that user enters in, into a variable
$id = $_POST['invoice']
How would I write an if statement to check to see if the number that user entered is in that array
I have tried doing in a for each loop
foreach($result as $value){
if($value == $id){
echo 'this';
}else{
continue;
}
is there a better way of doing this?
if (in_array($id, $results)) {
// ...
}
http://php.net/manual/en/function.in-array.php
Use in_array():
if (in_array($_POST['invoice'], $your_array)) {
... it's present
}
ok you can try this:
if ( in_array($id, $results))
{
// execute success
}
else
{
// execute fail
}
You can use in_array, like the others have suggested
if(in_array($id,$results)) {
//do something
} else {
$no_invoice = true;
}
but if you happen to want to use your array key for anything, you can kill two birds with one stone.
if($key = array_search($id,$results,true)) {
echo 'You chose ' . $results[$key] . '<br />';
}
Obviously for echoing you don't need my method - you could just echo $id - but it's useful for other stuff. Like maybe if you had a multi-dimensional array and element [0]'s elements matched up with element[1]'s elements.
If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:
if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}
if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);
for($ac=0; $ac<$arr; $ac++){
if($r[$ac]==$anr[$ac]){
$res=$res+5;
}
}
echo $res;
}
Not quite.
your way is good enough, it only needs to be corrected.
foreach($results as $value){
if($value == $id){
echo 'this';
break;
}
}
is what you really wanted

Differentiate associated array from regular array

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

php if array key exists inside multidimentional 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;
}

Categories