explode function and array element reading [duplicate] - php

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)

Related

Neat way to get last array element in PHP [duplicate]

This question already has answers here:
How to get the last element of an array without deleting it?
(33 answers)
Closed 8 years ago.
I'd like to get last element of an array in PHP.
I often do this:
$last = $this->array_of_stuff[count($this->array_of_stuff) - 1];
I'm not very happy with that though.
Any way to make the syntax shorter and avoid repeating code?
You can use end function for this case. See the manual
end($array)
You can use end()
<?php
$a = array("a", "b", "c");
echo end($a);
https://eval.in/188679

Is there a way to get just one element from array that is returned as a function? [duplicate]

This question already has answers here:
Accessing an array element when returning from a function
(3 answers)
Closed 9 years ago.
Say I have a function/method that returns an array, let's call it ArrayReturner(). But I only want the first element, [0]. Right now I'm doing something like...
$arrayReturned = ArrayReturner();
$varIWant = $arrayReturned[0];
Is there a way to do that in one line without the need for the temporary $arrayReturned array?
Try:
$arrayReturned = reset(ArrayReturner());
Depends on PHP's version you use.
If you're using PHP < 5.4, then you cannot get that, like ArrayReturner()[0]. That's only possible in PHP >= 5.4.
If you want your code to be portable, that would work with old and new versions, then you'd better stick with that code:
$arrayReturned = ArrayReturner();
$varIWant = $arrayReturned[0];

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

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'];

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