note 120659 deleted from control-structures.goto by salathe

From: Date: Mon, 21 Sep 2020 14:42:56 +0000
Subject: note 120659 deleted from control-structures.goto by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-215285@lists.php.net to get a copy of this message
Note Submitter: R. Borchmann ---- If you feel the urge to leave a nested loop with goto, better think again. Probably you've got a piece of your code that should be refactored into a function. Instead of <?php for ($i=0; $i<10; $i++) { for ($j=$i, $j<11; $j++) { if ( $data[$i] === $data[$j] ) goto foundit; } } echo "Sorry, no match"; goto nextAction; foundit: echo "Duplicate at $i and $j)"; nextAction: ?> you better write <?php list($success, $i, $j) = searchForDuplicate( $data ); if ($success) echo "Found it at ($i, $j)"; else echo "Sorry, no match"; function searchForDuplicate( &$data ) { for ($i=0; $i<10; $i++) { for ($j=$i, $j<11; $j++) { if ( $data[$i] === $data[$j] ) return [ true, $i, $j ]; } } return [false]; } ?> or return [$i, $j] and [-1, -1] if you don't like an extra $success variable. Refactoring into a function is cleaner and gives you an auto-documentation about what the loop is doing.

« previous php.notes (#215285) next »