The Little Guy Posted October 20, 2008 Share Posted October 20, 2008 say I have this: (5+5 I have code that will add on the last parenthesis to that, but it doesn't work. It works if there is at least one parenthesis on each side then it works, so these work: (5+5)) (5+5)+5) ((5+5)+5 but the top one doesn't $clp = substr_count($calc,'('); $crp = substr_count($calc,')'); echo '<h1>Uneven parenthesis count</h1>'; if($clp > $crp){ $f = ''; for($cc = $clp - $crp;$cc<$clp;$cc++){ $f .= ')'; } $nCalc = $calc.$f; }elseif($clp < $crp){ $f = ''; for($cc = $crp - $clp;$cc<$crp;$cc++){ $f .= '('; } $nCalc = $f.$calc; } Link to comment https://forums.phpfreaks.com/topic/129261-solved-add-missing-values/ Share on other sites More sharing options...
rhodesa Posted October 20, 2008 Share Posted October 20, 2008 it should be <= on both: for($cc = $clp - $crp;$cc<=$clp;$cc++){ ... for($cc = $crp - $clp;$cc<=$crp;$cc++){ Link to comment https://forums.phpfreaks.com/topic/129261-solved-add-missing-values/#findComment-670164 Share on other sites More sharing options...
The Little Guy Posted October 20, 2008 Author Share Posted October 20, 2008 but then it adds too many for the ones with more than one set of parenthesis. Link to comment https://forums.phpfreaks.com/topic/129261-solved-add-missing-values/#findComment-670175 Share on other sites More sharing options...
rhodesa Posted October 20, 2008 Share Posted October 20, 2008 yeah, looking at it again, the logic was off a little. try this out (i removed the IF statements since they aren't needed): <?php $cases = array( '5+5)', '(5+5))', '(5+5)+5)', '((5+5)+5', ); print '<table border="1">'; foreach($cases as $calc){ $clp = substr_count($calc,'('); $crp = substr_count($calc,')'); $nCalc = $calc; for($cc = $clp - $crp;$cc > 0;$cc--){ $nCalc .= ')'; } for($cc = $crp - $clp;$cc > 0;$cc--){ $nCalc = '('.$nCalc; } print '<tr><td>'.$calc.'</td><td>'.$nCalc.'</td></tr>'; } print '</table>'; ?> Link to comment https://forums.phpfreaks.com/topic/129261-solved-add-missing-values/#findComment-670185 Share on other sites More sharing options...
The Little Guy Posted October 20, 2008 Author Share Posted October 20, 2008 Cool, seems to be working! Link to comment https://forums.phpfreaks.com/topic/129261-solved-add-missing-values/#findComment-670194 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.