How to program without GoTo [duplicate] - php

This question already has answers here:
Is GOTO in PHP evil? [closed]
(11 answers)
Closed 8 years ago.
I know goto statements are bad, but I find that it is hard to not use them when programming. I am a new programmer, and I know they are bad practice, but what are some ways to get around using them? I know about IF ELSE statements, but what other tools are out there to help me avoid using GoTo's?

Goto is a feature new, since PHP 5.3. There is some very, very specific reasons to use them. You will find some Goto's in drivers or kernel codes, but I really can't see any reason to use it in usual CMS, Blog, Social Network, e-shop and so on...
If you will return a 404, you can use a "header('errorpage.php')", for instance. You can assign a flag.
} elseif ($event['response']->getStatusCode() == 404) {
$errorno = '404';
//goto a;
$thingsGoingWrong = true;
}
.
.
<?php if ($thingsGoingWrong) { doBazinga(); } ?>
Considering you are not using a prior version of PHP, there are some rules for Goto, like you can't enter in a loop, or switch statement.

Related

Do-While loop not stopping on request [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 4 years ago.
I've been learning PHP for over a year now and it's always the little things that seem to go disastrously wrong, or I just forget what I'm doing.
I've been using Do-While loops in a few projects but recently one I created just didn't work. Once I numbed it down to almost nothing I noticed it just isn't stopping according to user input.
do {
echo "Hi there\n";
echo "Echo\n";
$userInput = readline();
} while ($userInput = 'continue');
echo "Exit";
I don't understand what's going wrong but something is. From my understanding the program will echo twice, listen for the user's input and loop through again while the user types continue - if not then will echo Exit. What am I doing wrong? This is such a simple task and it's annoying me. All the other topics I've searched for don't seem to be helping.
You need to use
while ($userInput == 'continue');
instead of
while ($userInput = 'continue');
because you have used wrong operator (= [assign] instead of == [equals])

Currying in_array() in PHP [duplicate]

This question already has answers here:
Is it possible to curry method calls in PHP?
(8 answers)
Closed 5 years ago.
Don't necessarily have a problem with how PHP does this or anything, more just a question out of curiosity. I am familiar with functional programming but am by no means an expert. I am writing functions currently and although I have no requirement for them to be functional, that may change in the future. So best to be prepared I say.
My question is, how would you curry a function like in_array?
From what I understand we have two parameters, needle and haystack.
Both seem to be required when the function is called.
We must know the array we are searching at the start of the function, and we must also know what we are searching for.
To me it seems hard to force any partial application or currying solution whereby we might know one or the other at a later point.
I suppose you could have a non-generic function whereby you specify the needle within the function. I did see something about spattering in Google. How would you handle this if asked to rewrite the function and curry it? I know I specified PHP but I suppose any language is really fine as long as the specs are the same.
Well, it's relatively straightforward in PHP - almost the same as in any other language that treats functions as values. For example:
function create_search_by_array($arr) {
return function($needle) use ($arr) {
return in_array($needle, $arr);
};
}
$search_in_1_to_10 = create_search_by_array(range(1, 10));
var_dump($search_in_1_to_10(1)); // true
var_dump($search_in_1_to_10(10)); // true
var_dump($search_in_1_to_10(11)); // false
The only caveat here is use ($arr) construct: without it, the inner function won't be able to see the corresponding variable from an outer scope.

PHP - using global vs passing by reference [duplicate]

This question already has answers here:
Advantage of passing by reference opposed to using global?
(6 answers)
Closed 5 years ago.
Is there any practical difference between using globals and passing param by reference?
Simple example:
$my_var = 5;
$my_var2 = 3;
function add_one(&$i){
return $i++;
}
function add_one_global(){
global $my_var2;
return $my_var2++;
}
add_one($my_var);
echo "$my_var<br>";
add_one_global();
echo "$my_var2";
The output is:
6
4
Both of them modify global variable (aware that it should be avoided if possible), "add_one" seems to be a little bit more flexible, but apart from that is there any other difference?
Not really, there is no difference. What kind of difference did you expect? The only real difference is the one that you noticed yourself - the pass-by-reference is more flexible and doesn't pollute the global namespace.
If this is for a small one-off script that you need to run once and then discard, go for whichever is fastest for you.
If this is for something that will keep working for a while, pick the pass-by-reference. It will be a lot easier down the road when you need to do some modifications to the script (and that's a when, not an if).

add math operators in function php [duplicate]

This question already has answers here:
How to mathematically evaluate a string like "2-1" to produce "1"?
(9 answers)
Closed 9 years ago.
I'm kinda new to this but I was wondering if it is possible to add some dynamic calculation into a function as a parameter.
The thing is inside my function I am formatting stuff in a consistent way but each time I want to add a certain different calculation into the parameter.
<?php
function dynamicCalculator($calculation){
$result = $calculation;
//some formatting
return $result;
}
echo dynamicCalculator('(3x5)+1');
This doesn't work of course but if anyone has an idea how this could work I would love to hear it.
What you are looking for is the eval function.
eval('$result = (3*5)+1');
But beware to make sure you're not passing possibly harmful code to that function.
Your looking for RPN (Reverse Polish Notation)
Here is one example
http://pear.php.net/package/Math_RPN/
which would allow you to use
$expression = "(2^3)+sin(30)-(!4)+(3/4)";
$rpn = new Math_Rpn(); echo $rpn->calculate($expression,'deg',false);
And not have to use Eval
Use eval. eval("10+2") should return 12. Be careful though, you can also run PHP code with eval.
Someone else had a similar question on StackOverflow.
You could use this:
function dynamicCalculator($calculation) {
$result = eval($calculation);
return $result;
}

conditional statements as strings [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
echo inside if loop
I trying to code a trading system and i have a list of entry and exit strategies. To lessen the number of lines in the code I planned to put all my strategies into an array for each entry and exit. My array is like this
$enter_strats = array(
array('name'=>"macd",'strat'=>"/$divergence[/$key]>0.1;"),
);
I am including the conditional statements inside the array as above.
while I am looping thru everyday prices, I have to check for each entry strategy if they they are true. My if statement is like this
foreach($divergence as $key=>$value)
{
if($trade ==0)
{
foreach($enter_strats as $k =>$v)
{
$strat = $v['strat'];
$strat = str_replace("#","$",$strat);
eval("\$strat = \"$strat\";");
if ($strat)
{
$trade =1;
$book->save($key,$close[$key],$v['name']);
}
}
}
}
The problem since it is a string its always if is always evaluating it to true. I tried to put one more eval inside if but its of no use.
Please help to solve this problem, its is very essential. Thanks a lot.
That's because you're trying to lessen the number of lines in the code.
Arrays intended to keep data, not code.
As soon as you understand it, your code will be okay.
'strat' should contain only data. An operator and a number for instance.
keeping variable name in the string makes no sense.
especially if you have this variable already.
You have already have $divergence[$key] in your code.
So, 'strat' should be just array('>',0.1)

Categories