Converting some PHP code to javascript (foreach equivalent) [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
For each in a array. How to do that in javascript?
Hey I was needing some help with finding a good for each equivalent from PHP to javascript. I've tried using jQuery.each() but I'm not sure I've done it correctly.
Here is the code I've been needing to convert. I need to fix each foreach to javascript.
if(calculate){
// got complete, calculate possible solution
// use decimals? Does this work in the form?
foreach(values as valName1 => val1){
foreach(operands as op1){
foreach(values as valName2 => val2){
if(valName2 == valName1)
continue;
foreach(operands as op2){
foreach(values as valName3 => val3){
if(valName3 == valName1 ||
valName3 == valName2)
continue;
foreach(operands as op3){
foreach(values as valName4 => val4){
if(valName4 == valName1 ||
valName4 == valName2 ||
valName4 == valName3)
continue;
foreach(operands as op4){
foreach(values as valName5 => val5){
if(valName5 == valName1 ||
valName5 == valName2 ||
valName5 == valName3 ||
valName5 == valName4)
continue;
parentheses = -1;
if(solve(val5, op4, val4, op3, val3, op2,
val2, op1, val1, solution, parentheses)){
count++;
// Note that since solve() just returns the first result, we won't
// display all possible parentheses ordering when there are multiple
// solutions
if(find_all){
document.write(Solution(val5, op4, val4, op3, val3, op2,
val2, op1, val1, solution, parentheses, find_all);
}
else{
document.write(Solution(val5, op4, val4, op3, val3, op2,
val2, op1, val1, solution, parentheses, find_all);
break;
}
}
parentheses = -1;
}
parentheses = -1;
if(!find_all && count) break;
}
if(!find_all && count) break;
}
if(!find_all && count) break;
}
if(!find_all && count) break;
}
if(!find_all && count) break;
}
if(!find_all && count) break;
}
if(!find_all && count) break;
}
if(!find_all && count) break;
}
if(!count || find_all){
document.write( "Found " . count . " solutions.";
}
}

If you are looking for functions (eg. foreach) dealing with data-sets the underscore.js is a good choice.

Related

how to write single line if statement with multiple conditions?

I'm currently working on a foreach loop with nested if statements but I'm pretty sure there's a better way of writing these chunks of if statements.
I found this post: PHP if shorthand and echo in one line - possible?
Though this post is for single conditions, I would like to write mine in the same way(single lined).
I'm not that experienced in PHP myself so I'm sort of stuck on doing it the old fashioned way:
if(($colorLevel['name'] === 'ATTR_VPMCV13') && ($colorLevel['level'] >= 80))
{
$prominentSideNumberArray[] = 10;
}
elseif(($colorLevel['name'] == 'ATTR_VPMCV13') && ($colorLevel['level'] >= 60) && ($colorLevel['level'] <= 70)){
$prominentSideNumberArray[] = 8;
}
If someone could properly explain what code to use where and why, that could really help me, and/or others, out. I've looked at the manual but I just can't figure out what to use where.
There is no such thing like an "if shorthand".
?: is an operator, if is a control structure. They are different language concepts that have different purposes and do different things. An expression that contains the ternary conditional operator (?:) can always be rewritten as two expressions and an if/else statement. The vice-versa is usually not possible.
The code you posted can be written to be much easier to read if you extract the common checking of $colorLevel['name'] into a separate if that includes the rest of the tests, extract $colorLevel['level'] into a new variable with shorter name and make the conditions that use $colorLevel['level'] use the same rule:
$level = $colorLevel['level'];
if ($colorLevel['name'] == 'ATTR_VPMCV13') {
// Don't mix '<=' with '>=', always use '<='...
if (60 <= $level && $level <= 70) {
$prominentSideNumberArray[] = 8;
// ... and put the intervals in ascending order
} elseif (80 <= $level) {
$prominentSideNumberArray[] = 10;
}
}
If there are multiple if statements that verify different values of $colorLevel['name'] then the intention is more clear if you use a switch statement:
$level = $colorLevel['level'];
switch ($colorLevel['name'])
{
case 'ATTR_VPMCV13':
if (60 <= $level && $level <= 70) {
$prominentSideNumberArray[] = 8;
} elseif (80 <= $level) {
$prominentSideNumberArray[] = 10;
}
break;
case '...':
// ...
break;
default:
// ...
break;
}
You can achieve this by using a ternary operator. Look at the following code:
$prominentSideNumberArray[] = ((($colorLevel['name'] === 'ATTR_VPMCV13') &&
($colorLevel['level'] >= 80) )? 10 : (($colorLevel['name'] == 'ATTR_VPMCV13') &&
($colorLevel['level'] >= 60) && ($colorLevel['level'] <= 70)?8:"")) ;
EDIT As per comments and you have to compare same value its better to define name
$color_name = "ATTR_VPMCV13";
if($colorLevel['name'] == $color_name )
$prominentSideNumberArray[] = (($colorLevel['level'] >= 80)? 10 : (
($colorLevel['level'] >= 60) && ($colorLevel['level'] <= 70)?8:"")) ;
DEMO with different approach
EDIT
Keep in mind that this solution is less readable than if-else statement.

php - using strpos() to replace multiple comparisons in an if statement

Is it OK to replace multiple comparisons by using strpos()?
Example:
changing
if ( $linecounter == $extra1 || $linecounter == $extra2 || $linecounter == 5 )
{
...
}
to
$ok = ' ' . $extra1 . $extra2 . '5';
if ( strpos($ok, $linecounter) > 0 )
{
...
}
No, it's not OK because that's not what strpos is for. It's easy to find problematic examples in the general case (e.g. $linecounter == 15 and $extra2 == 1 -- the strpos check will succeed when it should not have).
If you want to lose the separate conditions so much, workable alternatives would be either a switch statement or in_array:
switch($linecounter) {
case $extra1: case $extra2: case 5:
// whatever
break;
}
if (in_array($linecounter, [$extra1, $extra2, 5])) {
// whatever
}
As an aside, using strpos with a greater-than-zero test like that is not good style. What you want to say is "if it's found in the string", so write exactly that and lose the "prefix a space" hack:
if ( strpos($extra1 . $extra2 . '5', $linecounter) !== false )

PHP Elseif Ternary Operators

I am trying to convert the following code into a Ternary Operator, but it is not working and I am unsure why. I think my problem is that I do not know how to express the elseif operation in ternary format. From my understanding and elseif is performed the same way as an if operation by using the format : (condition) ? 'result'.
if ($i == 0) {
$top = '<div class="active item">';
} elseif ($i % 5 == 0) {
$top = '<div class="item">';
} else {
$top = '';
}
$top = ($i == 0) ? '<div class="active item">' : ($i % 5 == 0) ? '<div class="item">' : '';
$top = ($i == 0) ? '<div class="active item">' : (($i % 5 == 0) ? '<div class="item">' : '');
you need to add parenthesis' around the entire else block
The Ternary Operator doesn't support a true if... else if... else... operation; however, you can simulate the behavior by using the following technique
var name = (variable === 1) ? 'foo' : ((variable === 2) ? 'bar' : 'baz');
I personally don't care for this as I don't find it more readable or elegant. I typically prefer the switch statement.
switch (variable) {
case 1 : name = 'foo'; break;
case 2 : name = 'bar'; break;
default : name = 'bas'; break;
}
Too late probably to share some views, but nevertheless :)
Use if - else if - else for a limited number of evaluations. Personally I prefer to use if - else if - else when number of comparisons are less than 5.
Use switch-case where number of evaluations are more. Personally I prefer switch-case where cases are more than 5.
Use ternary where a single comparison is under consideration (or a single comparison when looping), or when a if-else compare is needed inside the "case" clause of a switch structure.
Using ternary is faster when comparing while looping over a very large data set.
IMHO Its finally the developer who decides the trade off equation between code readability and performance and that in turn decides what out of, ternary vs. if else-if else vs. switch-case, can be used in any particular situation.
//Use this format before reducing the expression to one liner
$var=4; //Change value to test
echo "Format result: ";
echo($var === 1) ? 'one' : //if NB.=> $varname = || echo || print || var_dump(ternary statement inside); can only be (placed at the start/wrapping) of the statement.
(($var === 2) ? 'two' : //elseif
(($var === 3) ? 'three' : //elseif
(($var === 4) ? 'four' : //elseif
'false' //else
))); //extra tip: closing brackets = totalnumber of conditions - 1
// Then echo($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false')));
echo "<br/>";
var_dump("Short result: ", ($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false'))) );

How to accomplish this if then statement with less repetition?

I have something simple I'm trying to accomplish with less repetition.
By default, I want a div to be shown, however if $x == 1, then check to see if $y != 1, and if $y doesn't, then don't show the block.
However the best I can come up with is the following:
if($x) {
if($y != 1) {
echo '<div>display block</div>';
}
} else {
echo '<div>display block</div>';
}
This seems a bit repetitive.
I know I can tweak it a bit and do something like:
$displayBlock = '<div>display block</div>';
if($x) {
if($y != 1) {
echo $displayBlock;
}
} else {
echo $displayBlock;
}
But even still, I have a feeling that there is a way to do this whole if if else thing which I can't see right now.
How do you accomplish the above with less if statements? So: if $x != 1 (default), then show the displayBlock. if $x == 1, and $y != 1, then show the display block. If $x == 1 && $y == 1, then do not show the displayBlock.
if (!$x || $y != 1) echo $displayBlock;
+1 to zerkms's answer - it's on the money. To help you solve problems like this in the future, it might be handy to look at truth tables Karnaugh maps.
You essentially have two checks:
a) $x (coerced to true or false)
b) $y != 1
$y != 1
T F
$x T 1 0
F 1 1
So, from that you can see that if $x is falsey, or $y != 1 is true, then you should show the display block, hence:
if (!$x || $y != 1) echo $displayBlock;
In order to keep the amount of code down, you could use a more mathematical approach rather than logic; e.g.
<?php
if($x+$y != 2){echo $displayBlock;}
?>
The display box only stays off when the sum of x and y equals 2.
Check these out. http://www.php.net/manual/en/language.operators.logical.php
$displayBlock = '<div>display block</div>';
if((($x) && ($y != 1)) || (!$x)) {
echo $displayBlock;
}
How did we come to this solution?
Look at your statement, and dissect it logically:
If x is true ... and ... y is 1... then print.
Which brings us to:
(($x) && ($y != 1))
See? X is truth AND y is one. That brigns you down to
if (($x) && ($y != 1)) {
//Do that thing
} else {
if (! $x) {
//Do that thing
}
}
Which we can write simply as...
if (($x) && ($y != 1)) {
//Do that thing
} else { if (! $x) {
//Do that thing
}
Okay, so what's this say?
If conditionA do something, or if condition B do something.
Oh, there's an OR.
So, condtion A || condition B
Which of course, brings us back to...
if((($x) && ($y != 1)) || (!$x)) {
I put in more braces than required in there so you can see the flow of things.

Is there a simpler way to check if a variable equals a variety of numbers?

This is what i have currently
if ($j == 1 || $j == 2 || $j == 3)
Is there a simpler way of writing this. Something like...
pseudocode
if ($j == 1-3)
Here's one way using in_array()
if (in_array($j, array(1,2,3)))
{
//do something
}
Or how about using range() to make the array
if (in_array($j, range(1,3)))
{
//do something
}
However, building an array just to check a narrow, contiguous range like that is pretty inefficient. So how about simply:
if ($j >= 1 && $j <= 3)
{
//do something
}
If other values of $j will trigger different action, a switch might be more appropriate...
switch($j)
{
case 1:
case 2:
case 3:
//do something
break;
}
If it's a range, you can simply do:
if ($j >= 1 && $j <= 5) ...
Paul's good one, but if you have a large number then you may want to use range:
if (in_array($j, range(0, 100)))
{
}

Categories