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.
Related
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.";
}
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
}
}
<?php
namespace foo;
class bar{
public static function runner( $data )
{
extract ($data);
foreach( $elements as $element )
{
$varsToWipe = array_keys($element);
extract( $element );
/*
bunch of code using the variables extracted from $element, eg if( isset($runnerSpeed) )
*/
//now i want to be able to unset all the elements set from the extract within the foreach loop
foreach( $varsToWipe as $var )
{
//but what goes here in the unset function?
\unset( );
}
}
}
}
How can I unset the variables extracted from within the foreach loop in the runner method?
The contents of $data can vary and the vars need to be unset so as not used again on the next loop iteration. I know i can ref the array itself but would be quicker to write if this could work...
Thanks,
John
A simpler foreach example:
$array = range(0,6);
$i = 0;
foreach( $array as $a )
{
echo $i.' ';
if( $i == 0 )
{
$egg = true;
}
++$i;
if( isset($egg) )
{
echo 'eggs ';
}
}
will print
0 eggs 1 eggs 2 eggs 3 eggs 4 eggs 5 eggs 6 eggs
You could then add a removal of $egg from the globals as this is where is sits:
$array = range(0,6);
$i = 0;
foreach( $array as $a )
{
echo $i.' ';
if( $i == 0 )
{
$egg = true;
}
else
{
unset( $GLOBALS['egg'] );
}
++$i;
if( isset($egg) )
{
echo 'eggs ';
}
}
Now it would print:
0 eggs 1 2 3 4 5 6
But what do you unset when you are within a class method, where is the variable actually stored?
Don't use the extract() function in the first place and simply iterate over the given array.
<?php
class Foo {
public function runner($data) {
foreach ($data as $delta => $element) {
if ($element === "something") {
// do something
}
}
}
}
Of course you could unset something inside the array now, but why would you want to? I can't see a reason why because the array isn't passed by reference and isn't used after the loop so it will go out of scope and is simply collected by the garbage collector.
In case of nested arrays:
foreach ($data as $delta => $element) {
if (is_array($element)) {
foreach ($element as $deltaInner => $elementInner) {
// ...
Pretty late now but for reference.
You can unset() them directly with:
unset($$var);
What extract does is equivalent to:
foreach($arr as $key => $value) {
$$key = $value;
}
So to unset you do:
foreach(array_keys($arr) as $key) {
unset($$key);
}
But like mentioned, you don't need to unset() them as they are deleted when the function completes as they will become out of scope.
Also, extract() is totally fine as it (most likely) does not copy the data values, it just creates new symbols for each array key. PHP internally will only copy the values if you actually modify it ie. copy-on-write with reference counting.
You can off course test this using memory_get_usage() before and after you do extract() on a large 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;
I have a multidimensional array like this
$array['value'][1][1]
Now i would like to implement if loop like this
if ($value = $array['value'][1][1]) {
echo "It works";
}
Now it works if i assign the values like [1][1],[2][1].
Is it possible to compare the whole array.
I mean if the array looks like
array[value][1][1],array[value][2][1],..........,array[value][n][1]
It works should be echoed.
I tried like this.
if ($value = $array['value'][][]) {
echo "It works";
}
But its not working. Can anyone give me the correct syntax?
I'm not sure if this is what you're looking for but you could try this function
$value is 1 in your case
function($array,$value)
foreach($array['amazon'] as $val){
if($value != $val[1])return FALSE;
}
return TRUE;
}
The function runs through $array['amazon'][*] and checks condition for each value. If found FALSE for any it returns
Based on your comments of what you're trying to accomplish, I think the following may solve your dilemma. Let me know if I'm going the wrong direction with this or have any additional questions/concerns.
<?php
$forms = array(
'amazon' => array(
0 => array(
1 => 111,
),
1 => array(
1 => 222,
),
2 => array(
1 => 333
)
)
);
$value = 333;
$it_works = False;
foreach($forms['amazon'] as $array) {
if($array[1] == $value) {
$it_works = True;
break;
}
}
if($it_works === True) {
print 'It Works!';
}
?>
You can try this:
$itWorks = true;
for( $a = 0; $a < sizeof( $array[value] ); $a ++ ){
if ( $value != $array[value][$a][1] ){
$itWorks = false;
break;
}
}
if( $itWorks ){
echo "It works";
}
Of course you must replace [value] with a legitimate value
function check() {
for($i = 0; $i < count($array[$value]); $i++) {
if($value != $array[$value][$i][1])
return FALSE;
}
echo 'It works!';
}