How can I search in a 2d array if a value DOES NOT exist and if not, add the value in the 2d array?
I hav been trying using foreach
loop however the code adds many values as keys in the array.
Now I am trying using array_key_exists
but stil not luck.
array1 = [["aab","17"],["bbb","6"],["aac","5"],["aad","76"]];
if(array_key_exists('AAA', $array1)) {
echo "FOUND";
}else{
array_push($array1, ['AAA','1']);
}
print_r($array1); // [["aab","17"],["bbb","1"],["aac","5"],["aad","5"],['AAA','1']]
You can use PHP's array_search
$array1 = [["aab","17"],["bbb","6"],["aac","5"],["aad","76"]];
$found = false;
foreach($array1 as $a){
if(array_search('AAA',$a) !== false){
$found = true;
}
}
if(!$found){
array_push($array1, ['AAA','1']);
}
print_r($array1);