Jump to content

looping through 2 dim array


stijn0713

Recommended Posts

What is the easiest way to check if a certain 'column' of a two-dimentional array is holding only positive numbers?

 

I thought of looping throught that column with a for lus and doing a variable ++ if the number is > 0 and then in the end compare the variables number with the length of that column.

 

Is there something more 'efficient'?

Link to comment
https://forums.phpfreaks.com/topic/264752-looping-through-2-dim-array/
Share on other sites

I really don't understand your second sentence. But, with a mufti-dimensional array I can't think of any solution other than looping through each primary array. But, you can make it more efficient by exiting the loop as soon as the first non-positive number is encountered.

 

<?php

$all_positive = true;
foreach($theArray as $subArray)
{
    if($subArray['key_to_be_searched'] < 0)
    {
        $all_positive = false;
        break;
    }
}

if($all_positive)
{
    echo "All the elements were positive";
}
else
{
    echo "All the elements were not positive";
}

?>

 

If you need to do this for multiple columns, then I'd make it a function

<?php

  $array = array( array( 1,2,3,4), array(1,2,3,4,-1,-2));

  // loop over the outer
  foreach( $array as $innerKey => $innerArray )
  {
    // assume it's positive by default
    $isPositive = true;

    // loop over the inner
    foreach( $innerArray as $k=>$v )
    {
      // if value is negative
      if( $v < 0 )
      {
        $isPositive = false;
        break;
      }      
    }    

    echo " Key #" . $innerKey . " is " . ( $isPositive ? "positive" : "not positive\n" );
  }
?>

 

Output:

 

 

Key #0 is positive 
Key #1 is not positive

@seventheyejosh: The code you posted is checking every value/column of the sub-arrays and returning true/false for each sub-array. The OP stated he wanted to check

. . . if a certain 'column' of a two-dimentional array is holding only positive numbers

thanks for the replies, sorry if i misformuled but i had to check it like in the post of psycho. so like if all the values of a certain column are positive.

 

About my second sentence, i did it like this:

 

function checkOptimality ($tabel, $m, $n){
$b = 0;
for ($y = 3; $y <$n; $y++){
if ($tabel[$m-1][$y] < 0){
	$b++;
	}
}
if ($b === ($n - 3)){
return true;
}
else {
return false;	
	}
}

.

 

In the end it doesn't really matter if you do it with a for lus of foreach i guess.. but thanks for the replies, now i understand how to loop with the foreach.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.