John Davidson

How to check given value present in nested array in PHP?

0 comments
Message:


I am very new to the PHP, i want to check the value is present inside the associative array,please help me to acheive this thing.


public $array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
foreach($array as $key=>$condition){
if(in_array('myFunction',$array)){
//My logic
}
}


My Answer:
To check if a given value is present in a nested associative array in PHP, you can use a recursive function that traverses the array and checks each element for the value. Here's an example code snippet to achieve this:

php
function isValuePresent($array, $value) {
foreach ($array as $key => $val) {
if ($val === $value) {
return true;
} elseif (is_array($val)) {
if (isValuePresent($val, $value)) {
return true;
}
}
}
return false;
}

$array = [
'id' => 1,
'name' => 'John',
'value' => [
'details' => [
'age' => 25,
'city' => 'New York'
]
]
];

$valueToCheck = 'New York';

if (isValuePresent($array, $valueToCheck)) {
echo "Value '$valueToCheck' is present in the nested array.";
} else {
echo "Value '$valueToCheck' is not present in the nested array.";
}


In this code snippet, the `isValuePresent` function recursively checks each element of the array for the given value. If the value is found at any level of nesting, the function returns `true`, indicating that the value is present in the nested array. Otherwise, it returns `false`.

You can modify the `$array` and `$valueToCheck` variables to test with different values.

Rate this post

4 of 5 based on 8978 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us