key search in php multidimensional associative array - php

$array = array(
'the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=>2),
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
);
How to check zindex key exist in above php array.

You have a method called array_key_exists for that. Of course you need to do some (recursive) looping if you don't know how deep the array with the value is located.

Maybe you should thing on using array_walk_recursive function in this way
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>
this is just a print example taken from php.net, but easily you can adapt it to fit your needs (adding the array_key_exist in the callback function, for example)

I'm not completely sure what you're wanting here, so here are a variety of tests you can run on zindex. These all use a foreach loop and array_key_exists.
If you want to check each item in the outer array to see if it has a zindex:
This loops through each element, and simply checks to see if the element has a zindex key of some sort.
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
} else {
echo "Fail!! Key '$key' has no zindex!\n<br>\n";
}
}
If you are just looking for there to be any zindex key at all:
This loops through until it finds an element that has a zindex. If a zindex is found, the function returns true, otherwise it returns false.
function find_zindex( $array ) {
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
return true;
}
}
return false;
}
if( find_zindex( $array ) ) {
echo "A zindex was found\n<br>\n";
} else {
echo "Fail: no zindex was found\n<br>\n";
}
If you're looking for a particular zindex value in your array:
This loops through, looking for a particular zindex that has a particular value. If it is found, then the key for the outside array is returned. Otherwise null is returned.
function find_zindex( $array, $search_key ) {
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) && $element['zindex']==$search_key ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
return $key;
}
}
return null;
}
$key = find_zindex( $array, 3 );
if( $key ) {
echo "The zindex was found at '$key'\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
$key = find_zindex( $array, 4 );
if( $key ) {
echo "The zindex was found at '$key'\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
If you want an array of every key that has a particular zindex:
This loops through, building an array that contains every element that matches the supplied zindex search value. When done, it returns the new array of elements. If nothing is found, it returns an empty array that will test as false.
function find_zindex( $array, $search_key ) {
$result = array();
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) && $element['zindex']==$search_key ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
$result[] = $key;
}
}
return $result;
}
$key = find_zindex( $array, 3 );
if( $key ) {
echo 'The zindex was found at:';
print_r( $key );
echo "\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
$key = find_zindex( $array, 4 );
if( $key ) {
echo 'The zindex was found at:';
print_r( $key );
echo "\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
If you are often trying to find data by the zindex, you will want to redesign your array:
This creates a second array that just has references to the elements in the first array. If you run this, you can see that the data is shared because the one assignment will set 'name' to 'new_name' in both arrays. Notice that each element of the outer array now has both an index and a zindex.
This assumes every element in $array has a zindex and the value of the zindex is unique. If some elements don't have a zindex or have duplicate zindexes, then you will need to modify this some.
$array = array(
'the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'index'=>'the-1','zindex'=>2),
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'index'=>'the-2','zindex'=>1),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'index'=>'the-3','zindex'=>3)
);
$zarray = array();
foreach( $array as &$value ) {
$zarray[$value['zindex']] =& $value;
}
// optional: order the entries in zarray by their key
ksort($zarray)
print_r($array);
echo "\n<br>\n";
print_r($zarray);
echo "\n<br>\n<br>\n<br>\n<br>\n<br>\n";
$array['the-1']['name']='new_name';
print_r($array);
echo "\n<br>\n";
print_r($zarray);

Related

PHP Array Search with key values

I have following arrays :
<?php
$a=array(
"abc"=>array("red","white","orange"),
"def"=>array("green","vilot","yellow"),
"xyz"=>array("blue","dark","pure")
);
echo array_search(array("dark"),$a);
?>
How to get output of xyz in array list.
array_search returns false or the key. Since you have multiple dimensions you must loop through to get the lowest level.
Since we are in another dimension your return will actually be 1. For this reason, if array_search succeeds we must use the key that is defined in the foreach
<?php
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
foreach($a as $key=>$data){
if(array_search("dark",$data)){
echo $key;
}
}
Outputs: xyz
You can create one user-define function to check value
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
function search_data($value, $array) {
foreach ($array as $key => $val) {
if(is_array($val) && in_array($value,$val))
{
return $key;
}
}
return null;
}
echo search_data("dark",$a);
DEMO
Please try this
function searchMultiArray($arrayVal,$val){
foreach($arrayVal as $key => $suba){
if (in_array($val, $suba)) {
return $key;
}
}
}
$a = array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
echo $keyVal = searchMultiArray($a , "dark");

How to search if the key value in an array exists in another array, using PHP?

I need a help. I have two arrays. I need to check if the values in first array are present in second or not. The arrays are as:
$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
$childata=array(array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123));
Here, I need to check if each value from first array is present inside second array or not. If yes, then should return true else false at each time.
Here you go, you can use the in_array() for PHP.
$maindata=array( array('id'=>3),array('id'=>7),array('id'=>9) );
$childata=array( array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123) );
foreach( $maindata as $key => $value )
{
if( in_array( $value, $childata ) )
{
echo true;
}
else
{
echo false;
}
}
You could also remove the whole if else and replace with a single line.
echo ( in_array( $value, $childata ) ? true : false );
Reference -
http://php.net/manual/en/function.in-array.php
https://code.tutsplus.com/tutorials/the-ternary-operator-in-php--cms-24010
To check if an array contains a value:
if (in_array($value, $array)) {
// ... logic here
}
To check if an array contains a certain key:
if (array_key_exists($key, $array)) {
// ... logic here
}
Resources
in_array - PHP Manual
array_key_exists() - PHP Manual
Following code will return true only if all elements of main array exists in second array, false otherwise:
$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
$childata=array(array('id'=>3),array('id'=>7),array('id'=>11),array('id'=>123));
$match = 0;
foreach( $maindata as $key => $value ) {
if( in_array( $value, $childata ) ) {
$match++;
}
}
if($match == count($maindata)){
// return true;
} else {
// return false;
}
Use array_intersect
if(!empty(array_intersect($childata, $maindata)))
{
//do something
}
or
$result = count(array_intersect($childata, $maindata)) == count($childata);
Use array_column and array_intersect.
$first = array_column($maindata, 'id');
$second = array_column($childata, 'id');
//If intersect done, means column are common
if (count(array_intersect($first, $second)) > 0) {
echo "Value present from maindata in childata array.";
}
else {
echo "No values are common.";
}

How do i check if a declare array is empty?

I have an array called tagcat , like so
$tagcat = array();
....
while ( $stmt->fetch() ) {
$tagcat[$tagid] = array('tagname'=>$tagname, 'taghref'=>$taghref);
}
Using print_r($tagcat) i get the following result set
Array ( [] => Array ( [tagname] => [taghref] => ) )
Using var_dump($tagcat), i get
array(1) { [""]=> array(2) { ["tagname"]=> NULL ["taghref"]=> NULL } }
In php, i want to check if the array is empty. But when using the following conditions, it always finds something in the array, which is not true!
if ( isset($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
if ( !empty($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
How do i check if the array is empty?
Use array_filter
if(!array_filter($array)) {
echo "Array is empty";
}
This was to check for the single array. For multi-dimensional array in your case. I think this should work:
$empty = 0;
foreach ($array as $val) {
if(!array_filter($val)) {
$empty = 1;
}
}
if ($empty) {
echo "Array is Empty";
}
If no callback is supplied, all entries of $array equal to FALSE will be removed.
With this it only returns the value which are not empty. See more in the docs example Example #2 array_filter() without callback
If you need to check if there are ANY elements in the array
if (!empty($tagcat) ) { //its $tagcat, not tagcat
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
Also, if you need to empty the values before checking
foreach ($tagcat as $cat => $value) {
if (empty($value)) {
unset($tagcat[$cat]);
}
}
if (empty($tagcat)) {
//empty array
}
Hope it helps
EDIT: I see that you have edited your $tagcat var. So, validate with vardump($tagcat) your result.
if (empty($array)) {
// array is empty.
}
if you want remove empty elements try this:
foreach ($array as $key => $value) {
if (empty($value)) {
unset($array[$key]);
}
}

detect duplicate value in for each loop php

foreach( array_combine( $ContentArray, $fileDateArray ) as $Content_Individual_Filename => $File_Individual_Date )
{
}
I want to detect duplicate date in $File_Individual_Date. if duplicate date/value then run if condition otherwise run else. for example
foreach( array_combine( $ContentArray, $fileDateArray ) as $Content_Individual_Filename => $File_Individual_Date )
{
if( $File_Individual_Date === duplicateValue )
{
}
else
{
}
}
Just use array_count_values() to create a lookup table before you run through the loop.
$a = array_combine($ContentArray, $fileDateArray);
$counts = array_count_values($a);
foreach($a as $Content_Individual_Filename => $File_Individual_Date) {
if($counts[$File_Individual_Date] > 1) { // has duplicate
} else { // unique value
}
}

check if association keys exists in a particular array

I'm trying to build a function that checks if there's a value at a particular location in an array:
function ($array, $key) {
if (isset($array[$key]) {
return true;
}
return false;
}
but how can I accomplish this in a multi array? say I want to check if a value is set on $array[test1][test2]
Pass an array of keys, and recurse into the objects you find along the way:
function inThere($array, $keys)
{
$key = $keys; // if a single key was passed, use that
$rest = array();
// else grab the first key in the list
if (is_array($keys))
{
$key = $keys[0];
$rest = array_slice($keys, 1);
}
if (isset($array[$key]))
{
if (count($rest) > 0)
return inThere($array[$key], $rest);
else
return true;
}
return false;
}
So, for:
$foo = array(
'bar' => array( 'baz' => 1 )
);
inThere($foo, 'bar'); // == true
inThere($foo, array('bar')); // == true
inThere($foo, array('bar', 'baz')); // == true
inThere($foo, array('bar', 'bazX')); // == false
inThere($foo, array('barX')); // == false
Here is a non-recursive way to check for if a multi-level hashtable is set.
// $array it the container you are testing.
// $keys is an array of keys that you want to check. [key1,key2...keyn]
function ($array, $keys) {
// Is the first key set?
if (isset($array[$key]) {
// Set the test to the value of the first key.
$test = $array[$key];
for($i = 1; $i< count($keys); $i++){
if (!isset($test[$keys[$i]]) {
// The test doesn't have a matching key, return false
return false;
}
// Set the test to the value of the current key.
$test = $test[$keys[$i]];
}
// All keys are set, return true.
return true;
} else {
// The first key doesn't exist, so exit.
return false;
}
}
While I probably wouldn't build a function for this, perhaps you can put better use to it:
<?php
function mda_isset( $array )
{
$args = func_get_args();
unset( $args[0] );
if( count( $args ) > 0 )
{
foreach( $args as $x )
{
if( array_key_exists( $x, $array ) )
{
$array = $array[$x];
}
else
{
return false;
}
}
if( isset( $array ) )
{
return true;
}
}
return false;
}
?>
You can add as many arguments as required:
// Will Test $array['Test1']['Test2']['Test3']
$bool = mda_isset( $array, 'Test1', 'Test2', 'Test3' );
It will first check to make sure the array key exists, set the array to that key, and check the next key. If the key is not found, then you know it doesn't exist. If the keys are all found, then the value is checked if it is set.
I'm headed out, but maybe this. $keys should be an array even if one, but you can alter the code to check for an array of keys or just one:
function array_key_isset($array, $keys) {
foreach($keys as $key) {
if(!isset($array[$key])) return false;
$array = $array[$key];
}
return true;
}
array_key_isset($array, array('test1','test2'));
There's more universal method but it might look odd at first:
Here we're utilizing array_walk_recursive and a closure function:
$array = array('a', 'b', array('x', 456 => 'y', 'z'));
$search = 456; // search for 456
$found = false;
array_walk_recursive($array, function ($value, $key) use ($search, &$found)
{
if ($key == $search)
$found = true;
});
if ($found == true)
echo 'got it';
The only drawback is that it will iterate over all values, even if it's already found the key. This is good for small array though

Categories