Jump to content

[SOLVED] freak loop, (acts differently on using nested functions..) why??


dsaba

Recommended Posts

<?php
function findGreaterThanInArr($arr, $num) { //returns 1st key in arr if the value is > than num
foreach ($arr as $k => $number) {
	if ($number > $num) {
		$foundNum = $k;
		break;
	}
}
if (isset($foundNum)) {
return $foundNum;
} else {
return FALSE;
}
}


function freakLoop() {
$startArr = array(0, 1, 2, 3, 4, 5);
$endArr = array(5,8,3,9,3);

foreach ($startArr as $key => $start) {
	$endKey = findGreaterThanInArr($endArr, $start); //doesnt stop looping
	//$endKey = 'hello'; //this one does
	echo "the key is: $key<br>";
	if ($endKey != FALSE) {
	die();
	}
}
}


//run the thing:
freakLoop();
?>

 

 

Ok see the above code, see the difference in the loop when you uncomment/comment these two lines:

$endKey = findGreaterThanInArr($endArr, $start); //doesnt stop looping

$endKey = 'hello'; //this one does

 

in both cases $endKey will not != FALSE , but in the case of calling the function, it continues looping ..very weird behavior, how do I get it to not do this??

 

Whats wrong?

yes it enters the if statement when endKey = 'hello' and then it dies... (nothing is wrong with this)

 

the problem is that when  call the function findGreaterThanInArr() it also should evaluate to != FALSE, yet it does not enter the if statement and does not die()

 

why does it do this?

yes it enters the if statement when endKey = 'hello' and then it dies... (nothing is wrong with this)

why? because exactly what you said 'hello' is evaluated to != FALSE

 

the problem is that when I call the function findGreaterThanInArr() it also should evaluate to != FALSE, yet it does not enter the if statement and does not die()

 

why does it do this?

the endArr once run through the findGreaterThanInArr() function should always return an integer number or in other words != FALSE

 

so as far as we're concerned shouldn't the if($endKey != FALSE) treat the endKey variable the SAME, whether its hello or an integer value from the function

figured it out.. and you didn't daniel!!

 

the problem is:

in the first iteration findGreaterThanInArr() does indeed return an integer value, and this integer value is the first key of the $endArr , which is of course 0

 

0 just also happens to evaluate to Boolean False, and this is why the statement fails

 

if the first element of the $endArr had had a different key other than 0, it would have worked

 

Solved! :)

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.