PHP - actually execute value of variable - php

I have an array of fractions:
$fractions = array('1/8', '1/4', '1/2');
Is there any way that I can get PHP to actually perform the division to get a decimal value?
Something like:
foreach($fractions as $value) {
$decimal = [the result of 1 divided by 8, or whatever the current fraction is in value];
}

The way you have it, you should just explode and do your division:
foreach($fractions as $value) {
$exp = explode('/',$value);
$decimal = $exp[0] / $exp[1];
}
You could also eval(), but I usually try not to do that. It is a performance hit as well.

You can call eval():
$fractions = array('1/8', '1/4', '1/2');
foreach($fractions as $value) {
$decimal = eval("return $value;");
echo "$value = $decimal\n";
}

Related

PHP substr by string, not by length

I am using this code
substr(trim($val), 0, 2).'/'.substr(trim($val), 0, 4).'/'.trim($val);
to convert
a.b.c.
to
a. / a.b. / a.b.c.
This obviously does not work as soon as I get double digits like a.bb.c., which results in
a. / a.bb / a.bb.c.
(dot is missing!) instead of
a. / a.bb. / a.bb.c.
Is there a way to extract/trim parts not based on length, but on the dots?
using explode and a foreach you can make it recursive, like this:
$val = 'aa.bv.cc.dd';
$vals = explode('.',$val);
$result = [];
foreach($vals as $k => $v) {
if(trim($v) === '') continue;
$result[] = ($k > 0 ? $result[$k-1] : '').$v.'.';
}
echo implode(' / ',$result);
in this way you don't need to worry about the amount of letter after each dot and about the amount of segments, and you can handle something like "a.b" or "a.b.c" or "aaa.bbb.ccc.ddd.eeeee" letting the script do all the job for you ;)
<?php
$data='a.b.c.';
$data=explode('.',$data);
$newData=array(
$data[0].'. ',$data[0].'.'.$data[1].'. ',$data[0].'.'.$data[1].'.'.$data[2].'.'
);
$newData = implode("/", $newData);
echo $newData;
And the output is :
a. /a.b. /a.b.c.

Split the decimal places in php

I am getting value in this format 2.00. I want to show the value as 2.How can i do so using php? My code to get value form the database is following and i am using floor function but evrytime i get value 0.
code
while ($row = oci_fetch_array($rcv, OCI_ASSOC+OCI_RETURN_NULLS))$basic_info[]=$row;
foreach ($basic_info as $x)
{
$serial=$x['SERIAL'];
$in = floor($serial);
}
echo "$in"
value in the database:
2.00
desired output:
2
currentoutput:
0
Use number_format() for that
number_format($x['SERIAL'], 0);
You can convert your $in value in int.
while ($row = oci_fetch_array($rcv, OCI_ASSOC+OCI_RETURN_NULLS))$basic_info[]=$row;
foreach ($basic_info as $x)
{
$serial=$x['SERIAL'];
$in = floor($serial);
}
echo (int)$in; // here is change.
Use typecasting.
$in = intval($serial);
Or
$in = (int) $serial;
while ($row = oci_fetch_array($rcv,OCI_ASSOC+OCI_RETURN_NULLS))$basic_info[]=$row;
foreach ($basic_info as $x){$serial=$x['SERIAL'];
$in = (int) $serial;} echo "$in";

Iterate on PHP variable (list/array) then output the index based on its value

Using the following example in PHP:
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
1) I would like to iterate on the 4 values in $priv. Would 'foreach' be the correct way to do it?
2) If the value is higher than a given number, I would like to echo the index of this value. Not sure how to do it. The comparaison must be INT (not string).
Ex. using "30" it would output:
PAGE_C
PAGE_D
Is it possible? Or maybe I am not using the correct container for what I'm trying to do ?
PS. How would you call the type of "$priv" in this example ? An array ? An indexed variable ? A dictionary ? A list ?
Thank you.
basically:
<?php
function foo($var){
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
$out='';
foreach ($priv as $k=>$v){
if ($v >$var){
$out .= $k.'<br>';
}
}
return $out;
}
echo foo('30');
demo: http://codepad.viper-7.com/GNX7Gf
Just create an array with the letters to iterate over.
$letters = array('A','B','C','D');
for($i=0;$i<count($letters);$i++) {
if($priv['PAGE_' . $letters[$i]] > /*value*/) {
echo $priv['PAGE_' . $letters[$i]];
}
}
$priv is an array.
Also, it's not too clear to me what you are exactly trying to do. Are you trying to echo the value of the array element if it's greater than a constant value?
We could do it using PHP builtin array functions. Its good to use builtin functions if possible in case of performance.
array_walk will do the trick for you. In this case $priv is an associative PHP array. Following is the one line script that will do what you want to achieve:
$input = 30;
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
array_walk($priv, function($value, $key, $input){ if($value > $input) echo $key . '<br>';}, $input);

PHP From string to two variables

In my db there is a table that have some values like this[string]
100/100
50/100
40/80
7/70
I need to change this values in
100%
50%
50%
10%
How can i do this using only PHP/mysql code?
EDIT:this is the code:
foreach ($html->find('div.stat') as $status_raw){
$status = $tag_pic_raw->src;
$status = mysql_real_escape_string($status);
$data->query("INSERT IGNORE INTO `tb` (`value`) VALUES ('".$status."')");
}
I have used a DOM inspector to get info from another site
Used explode() combined with some math.
$str = '40/80';
$vals = explode('/', $str);
$percent = (($vals[0] / $vals[1]) * 100).'%';
echo $percent;
use explode() to divide up the values and then math them.
foreach($array as $val) // assuming all the (##/##) values are in an array
{
$mathProblem = explode("/", $val);
echo (intval($mathProblem[0]) / intval($mathProblem[1]) * 100)."%<br />";
}
You can set up a function similar to this:
function math($one)
{
$new = explode("/", $one);
$math = $new[0] / $new[1];
$answer = $math * 100;
return $answer."%";
}
Then every time you need to query something, you can do it simply by doing this:
foreach ($results as $r)
{
echo math($r);
}
This just makes it (I think) tidier and easier to read.
Use explode() :Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter( / in this case).
$arr=array('80/100','50/100','40/80');
foreach($arr as $str){
$values = explode('/',$str);
echo ((int)$values[0]/(int)$values[1])*100.'%<br/>';
}

Find number which is greater than or equal to N in an array

If I have a PHP array:
$array
With values:
45,41,40,39,37,31
And I have a variable:
$number = 38;
How can I return the value?:
39
Because that is the closest value to 38 (counting up) in the array?
Regards,
taylor
<?php
function closest($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array); // or return NULL;
}
?>
Here is a high-level process to get the desired results and work for any array data:
Filter the array keeping on values greater than or equal to the target and then select the lowest remaining value. This is the "best" value (which may be "nothing" if all the values were less) -- this is O(n)
Alternatively, sort the data first and see below -- this is O(n lg n) (hopefully)
Now, assuming that the array is sorted ASCENDING, this approach would work:
Loop through the array and find the first element which is larger than or equal to the target -- this is O(n)
And if the array is DESCENDING (as in the post), do as above, but either:
Iterate backwards -- this is O(n)
Sort it ASCENDING first (see fardjad's answer) -- this is O(n lg n) (hopefully)
Iterate forwards but keep a look-behind value (to remember "next highest" if the exact was skipped) -- this is O(n)
Happy coding.
EDIT typo on array_search
Yo... Seems easy enough. Here's a function
<?php
$array = array(45,41,40,39,37,31);
function closest($array, $number){
#does the array already contain the number?
if($i = array_search( $number, $array)) return $i;
#add the number to the array
$array[] = $number;
#sort and refind the number
sort($array);
$i = array_search($number, $array);
#check if there is a number above it
if($i && isset($array[$i+1])) return $array[$i+1];
//alternatively you could return the number itself here, or below it depending on your requirements
return null;
}
to Run echo closest($array, 38);
Here's a smaller function that will also return the closest value. Helpful if you don't want to sort the array (to preserve keys).
function closest($array, $number) {
//does an exact match exist?
if ($i=array_search($number, $array)) return $i;
//find closest
foreach ($array as $match) {
$diff = abs($number-$match); //get absolute value of difference
if (!isset($closeness) || (isset($closeness) && $closeness>$diff)) {
$closeness = $diff;
$closest = $match;
}
}
return $closest;
}
Do a linear scan of each number and update two variables and you'll be done.
Python code (performance is O(N), I don't think it's possible to beat O(N)):
def closestNum(numArray, findNum):
diff = infinity # replace with actual infinity value
closestNum = infinity # can be set to any value
for num in numArray:
if((num - findNum) > 0 and (num - findNum) < diff):
diff = num - findNum
closestNum = num
return closestNum
Please add null checks as appropriate.
If you really want the value that's "closest" in distance, even if it's a lesser value, try this, which #Jason gets most of the credit for.
Imagine a scenario when you want the closest number to 38.9 in the following:
$array = array(37.5, 38.5, 39.5);
Most of the solutions here would give you 39.5, when 38.5 is much closer.
This solution would only take the next highest value if what you're looking is in the exact middle between two numbers in the array:
function nearest_value($value, $array) {
if (array_search($value, $array)) {
return $value;
} else {
$array[] = $value;
sort($array);
$key = array_search($value, $array);
if ($key == 0) { return $array[$key+1]; }
if ($key == sizeof($array)-1) { return $array[$key-1]; }
$dist_to_ceil = $array[$key+1]-$value;
$dist_to_floor = $value-$array[$key-1];
if ($dist_to_ceil <= $dist_to_floor) {
return $array[$key+1];
} else {
return $array[$key-1];
}
}
}
What it lacks in elegance, it makes up for in accuracy. Again, much thanks to #Jason.
Try this simple PHP function:
<?php
function nearest($number, $numbers) {
$output = FALSE;
$number = intval($number);
if (is_array($numbers) && count($numbers) >= 1) {
$NDat = array();
foreach ($numbers as $n)
$NDat[abs($number - $n)] = $n;
ksort($NDat);
$NDat = array_values($NDat);
$output = $NDat[0];
}
return $output;
}
echo nearest(90, array(0, 50, 89, 150, 200, 250));
?>
I made a shorter function for that:
function nearestNumber($num, $array) {
if(!in_array($num, $array)) $array[] = $num;
sort($array);
$idx = array_search($num, $array);
if(($array[$idx] -$array[$idx-1]) >= ($array[$idx+1] -$array[$idx])) return $array[$idx+1];
else return $array[$idx-1];
}
Works great in my case: $array = array(128,160,192,224,256,320); $num = 203 :)
It's taking the nearest number and if there's the same distance between two numbers (like 208 for my example), the next highest number is used.
+1 to Jason.
My implementation below, but not as brisk
$array = array(1,2,4,5,7,8,9);
function closest($array, $number) {
$array = array_flip($array);
if(array_key_exists($number, $array)) return $number;
$array[$number] = true;
sort($array);
$rendered = array_slice($array, $number, 2, true);
$rendered = array_keys($rendered);
if(array_key_exists(1, $rendered)) return $rendered[1];
return false;
}
print_r(closest($array, 3));
You could use array_reduce for this, which makes it more functional programming style:
function closest($needle, $haystack) {
return array_reduce($haystack, function($a, $b) use ($needle) {
return abs($needle-$a) < abs($needle-$b) ? $a : $b;
});
}
For the rest, this follows the same principle as the other O(n) solutions.
Here is my solution.
$array=array(10,56,78,17,30);
$num=65;
$diff=$num;
$min=$num;
foreach($array as $a){
if( abs($a-$num)< $diff ){
$diff=abs($a-$num);
$min=$a;
}
}
echo $min;

Categories