detect duplicate value in for each loop php - 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
}
}

Related

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 to find which if statement is met

I have the following if statement
if ( $missCh[0]['type']==4 OR $missCh[1]['type'] == 4 OR $missCh[2]['type'] == 4 ) {
echo 'go ahead';
}
I would like to find out if $missCh[0] or [1] or [2] is meeting the statement so that I can then ask if($missCh[X]['value]==3) but I don't know which part of the array holds true.
$types = array( $missCh[0]['type'], $missCh[1]['type'], $missCh[2]['type'] );
foreach ( $types as $key => $val ) {
if ( $val == 4 ) $fours[] = $key;
}
foreach ( $types as $key => $val ) {
if ( in_array( $key, $fours ) ) continue;
if ( $val == 3 ) $threes[] = $key;
}
print_r( $fours );
print_r( $threes );
I would like to find out if $missCh[0] or [1] or [2] is meeting the statement
AS you currently have it, you're not going to be able to manage this within the script as you currently allow the echo to be actioned if ANY of the criteria return TRUE.
If you want to action something based on what a particular array value is individually, you'll need to check each individually and action as appropriate:
if($missCh[0]['type']==4)
{
//Do something
}
elseif ($missCh[1]['type']==4)
{
//Do something
}
elseif($missCh[2]['type']==4)
{
//Do something
}
If appropriate, your final elseif could be just else, which would then be a catch all if none of the previous checks returned TRUE.
I've isolated the responsibility to check the if in a function. That function echoes "go ahead" and return the index $miss[$i]['type'] which is equals to 4.
<?php
$miss[0]['type'] = 2;
$miss[1]['type'] = 4;
$miss[2]['type'] = 5;
function goAhead($miss) {
for($i=0;$i<=count($miss);$i++) {
if($miss[$i]['type']==4) {
echo 'go ahead';
return $i;
}
}
}
$i = goAhead($miss);
echo $i;
This solution will work with one or infinite indexes or $miss array. This means that you will never need to refactor this code if $miss array will growth.

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

Assign value to double array

I have an issue assigning values to an array of arrays to add duplicates into the same values. Code is as following:
if( isset($rowsarray) && 0 < count($rowsarray) ) {
foreach ( $rowsarray as $rowt ) {
if( $version == $rowt[0] ) {
$rowt[1] += $success;
$rowt[2] += $failure;
$noDuplicate = false;
break;
}
}
}
if( true == $noDuplicate) {
$rowsarray[] = array($version, $success, $failure);
}
So if it's the first occurence of a version I just add it, otherwise I just increas the success and failure rate in the array. I have tried foreach ( $rowsarray as $key => $rowt ) without success as the "internal" array doesnt seem to be affected here. I am total new to php so I guess it's a rather simple solution but for now it takes only the first version access and all the other is inreased inside the loop but not outside it.
You're trying to modify a temporary array created by foreach(), which means $rowt is trashed/replaced on every iteration. You can work around it with a reference or a modified foreach:
foreach ( $rowsarray as &$rowt ) {
^----
$rowt[1] += $success;
or, less troublesome:
foreach($rowsarray as $key => $rowt) {
$rowsarray[$key][1] += $success;
You can simplify this check with:
if( isset($rowsarray) && 0 < count($rowsarray) ) {
with
if( ! empty( $rowsarray ) ){
And then,
foreach ( $rowsarray as $key => $rowt ) {
if( $version == $rowt[0] ) {
$rowsarray[$key][1] += $success;
$rowsarray[$key][2] += $failure;

key search in php multidimensional associative array

$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);

Categories