add math operators in function php [duplicate] - php

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;
}

Related

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).

Moving from preg_replace to preg_replace_callback [duplicate]

This question already has answers here:
Replace preg_replace() to preg_replace_callback() [duplicate]
(2 answers)
Closed 5 years ago.
I've had a good look through all the previous topics and I don't understand enough PHP to use them to answer my questions so sorry in advance if this is really simple!
{
$content = preg_replace('/\$([\w]+)/e', '$0', $this->getTemplateStyle());
$custom_css = $this->getCustomCSS();
return $content.$custom_css;
}
And I need to replace preg_replace with preg_replace_callback. I know it's not a simple switch and that I need to add more to the code, but I don't know what to add. Thanks in advance for your help.
[SOLVED]
You seem to be trying to inject variables from the current scope into your string. I'll leave aside why this is a bad idea and assume there is no user input involved. First get the current scope:
$scope = get_defined_vars();
Next use the callback:
preg_replace_callback('/\$(\w+)/',function($m) use ($scope) {if( isset($scope[$m[1]])) return $scope[$m[1]]; else return $m[0];}, $this->getTemplateStyle());
Job done. – #Niet the Dark Absol

One line code to get one value from function that returns an array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Parse error on explode('-','foo-bar')[0] (for instance)
In PHP there are functions that return an array, for example:
$a = parse_url("https://stackoverflow.com/q/9461027/87015");
echo $a["host"]; // stackoverflow.com
My question is how to combine the above two statements into a single statement. This (is something that works in JavaScript but) does not work:
echo parse_url("https://stackoverflow.com/q/9461027/87015")["host"];
Note: function array dereferencing is available since PHP 5.4; the above code works as-is.
You can do a little trick instead, write a simple function
function readArr($array, $index) {
return $array[$index];
}
Then use it like this
echo readArr(parse_url("http://stackoverflow.com/questions/9458303/how-can-i-change-the-color-white-from-a-uiimage-to-transparent"),"host");
Honestly, the best way of writing your above code is:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["scheme"];
echo $a["host"];
Isn't that what I originally posted?
Yes. Depending on context you may want a better name than $a (perhaps $url), but that is the best way to write it. Adding a function is not an attractive option because when you revisit your code or when someone reads your code, they have to find the obscure function and figure out why on earth it exists. Leave it in the native language in this case.
Alternate code:
You can, however, combine the echo statements:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a['scheme'], $a['host'];

explode function and array element reading [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php explode and array index
I am new to PHP and would like to ask if there is a way to
write a php code like
$lengthofstay = ($duration <= 0 ? 'optional' : explode("_", $duration )[0]);
i mean calling the explode function and at the sametime reading the first element of resulting array.
it would be possible in 5.4
but your code is as ugly as hell.
there is nothing good in writing all the code in one line.
Write in in three lines and when you come across it in a week, you wouldn't stumble upon it, puzzled.
if ($duration <= 0)
$lengthofstay = 'optional';
} else {
list($lengthofstay) = explode("_", $duration, 1);
}
nothing wrong with it.
if you want to make it strictly one-liner - create a function. and then call it
$lengthofstay = get_length_of_stay($duration);
it's shorter than your cunning construct and way more readable
You might want to use the limit-parameter from explode:
explode("_", $duration, 1)

Categories