I have the function get_price_data(); which gives "0,11\u20ac" as return value.
The "0,11" is not static.
I want to do some maths with "0,11" from the string below.
My Code shown down below does not work how i want it to. Has someone any idea how i can complete this task ? I am very new to php.
<?php
function get_price_data() {
$json = file_get_contents("http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=Chroma%202%20Case");
$decode = json_decode($json,1);
echo $decode['median_price'];
}
$string=get_price_data();
$string2 = str_replace("\u20ac","",$string);
echo $string2 * 1000 - 120;
?>
<?php
function get_price_data() {
$json = file_get_contents("http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=Chroma%202%20Case");
$decode = json_decode($json,1);
return $decode['median_price']; // return here instead of echo.
}
You are somewhat correct that this return is necessary because this is a function. A return statement is not specifically required in a PHP function (functions will return null by default if there is no explicit return value.) The reason you need it to return is that you are using its returned value in this statement:
$string=get_price_data();
With echo instead of return, $string will be set to null here, and any subsequent operations on it will obviously not do what you intended.
If you change your function to return the value of $decode['median_price'], then $string=get_price_data(); will assign 0,11€ to $string, and then your replacements and calculations should work as expected.
$string=str_replace(array('€','\u20ac'),'',$string);
$string = str_replace(",",".",$string); // replace , with . as noted by mertizci
echo $string * 1000 - 120;
?>
Because of the comma in the changed price value, PHP cant do math things on it. You should change the comma with dot too.
Your code should be (edited):
<?php
$string=get_price_data();
$string=str_replace(array('€','\u20ac'),'',$string);
$string = str_replace(",",".",$string);
echo $string * 1000 - 120;
?>
Related
I have this code in php -:
function pregRepler($matches)
{
* do something
}
$str = preg_replace_callback($reg_exp,'pregRepler',$str);
When in function pregRepler, i would want to know the current match number like if it is the first match or the second or anything...
How do i do it.??
Try something like this:
function pregRepler($matches) {
static $matchcount = 0;
// do stuff
$matchcount++;
}
This works better with an anonymous function, as I mentioned in my answer to your other question, as this will avoid problems if you have multiple calls to preg_replace_callback.
You need to share a $count variable between both variable scopes, for example by using a variable alias:
$callback = function($matches) use (&$count) {
$count++;
return sprintf("<%d:%s>", $count, $matches[0]);
};
echo preg_replace_callback($pattern, $callback , $subject, $limit = -1, $count);
Before invoking, $count is equal to 0. After invoking $count is set to the number of replacements done. In between you can count up in your callback. You can also set to zero again when calling another time.
See it in action
See http://php.net/preg_replace_callback
$repled = 0;
function pregRepler($matches)
{
* do something
global $repled;
$repled++;
}
$str = preg_replace_callback($reg_exp,'pregRepler',$str);
Just count from a global variable.
I am trying to get a string to a float so I can do math with it. I have tried many methods including floatval(). The answers always return to a big, fat, 0. I have also tried casting and get the same result. I have tried it with single variables and arrays. Here is the current code I am wrestling with:
<?php
$sim = array("$1.99","$0.75","$0.25");
for($i=0;$i<=2;$i+=1)
$som[$i] = floatval($sim[$i]);
for($i=0;$i<=2;$i+=1)
{
echo $som[$i];
echo "<br/>";
}
?>
Start by removing the dollar sign first with str_replace('$', '', $sim[$i])
You could also use substr to get rid of the $ in your string.
$sim = array("$1.99","$0.75","$0.25");
for($i=0;$i<=2;$i+=1)
$som[$i] = (float)(substr($sim[$i], 1));
for($i=0;$i<=2;$i+=1)
{
echo $som[$i];
echo "<br/>";
}
Here are some useful links.
http://us2.php.net/language.types.type-juggling
http://us2.php.net/manual/en/language.types.string.php#language.types.string.conversion
I want to prepend a "0" in front of a $_POST
$currency = $_POST['Currency']; // lets say 900
$currency = "0".$currency;
echo $currency;
It should have returned 0900 but it returns 900.
Any ideas?
EDIT
This is the full function
function validate(){
$ref = $this->input->post('Ref');
$shop = $this->input->post('Shop');
$amount = $this->input->post('Amount')*1000;
//$currency = $this->input->post('Currency');
//$currency = $_POST['Currency']; // lets say 900
//$currency = "0".$currency;
$currency = str_pad($_POST['Currency'],4,'0',STR_PAD_LEFT);
$query = $this->db->query("SELECT * FROM shop_validation WHERE merchant_ref = '$ref' ");
if($query->num_rows() > 0) {
$row = $query->row_array();
$posts = "";
foreach ($_POST as $name => $value) {
$posts .= $name." / ".$value;
}
$this->db->query("INSERT INTO transactions (shop,amount,currency,posts) VALUES ('$shop','$amount','$currency','$posts')");
if($row['merchant_ref'] != $ref)
{
echo "[NOTOK]";
return;
}
if($row['merchant_id'] != $shop)
{
echo "[NOTOK]";
return;
}
if(trim($row['amount']) != $amount)
{
echo "[NOTOK]";
return;
}
if($row['currency_code'] != $currency)
{
echo "[NOTOK]";
return;
}
echo "[OK]";
}
}
EDIT
This script run on Codeigniter framework
If what you want is to ensure that the input has a set number of digits, with leading zeros, I wrote a tip some time ago that does exactly that:
<?php
$variable = sprintf("%04d",$_POST['Currency']);
?>
This, will echo leading zeros until the $variable is 4 characters long. Here are some examples:
If $_POST['Currency'] has a value of
'3' it would echo '0003'
If $_POST['Currency'] has a value of
'103' it would echo '0103'
If $_POST['Currency'] has a value of
'3103' it would echo '3103'
Which is good even if the amount of characters is longer than 4 (in your case) since it would simply ignore the function and not add anything in front of it. Hope it helped :)
You might want to use the PHP's str_pad() function like that
$currency = str_pad($_POST['currency'],4,'0',STR_PAD_LEFT)
See php manual for details
Your problem is auto-casting, where a variable can be a string or a number value and php guesses which one you cant. Your currency variable is being used as a string when you do string contatenation on it with the dot operator, but then when you echo it it assumes it to be an integer and throws you the integer value. You could echo (string)$currency or use the str_pad() or printf() function to get more useful output values.
EDIT: The code in the question actually works as expected for me. You must be simplifying the example and your actual output function is something other than what you present here, because in that code the auto typecasting stuff works fine.
I have a whole bunch of percentages stored as XX% (e.g. 12%, 50%, etc..) I need to remove the percentage sign and then multiply the percent against another variable thats just a number (e.g. 1000, 12000) and then output the result. Is there a simple way to strip the percentage sign and then calculate the output with PHP? Or should I consider some sort of JS solution?
You could use rtrim():
$value = ((int) rtrim('12%', '%')) * 1000';
Edit
You don't strictly need to call rtrim() , as it casts to an int ok with the percentage sign. It is probably cleaner to strip it though.
var_dump (12 === (int) '12%');
//output: bool(true)
You can make use of preg_replace_callback as:
$input = '12%, 50%';
$input = preg_replace_callback("|(\d+)%|","replace_precent",$input);
echo $input; // 12000, 50000
function replace_precent($matches) {
return $matches[1] * 1000;
}
Try this:
$number = str_replace('%', '', '100%');
$result = intval($number) * 5000; // or whatever number
echo $result;
If you use trim() or str_replace() in PHP you can remove the percent sign. Then, you should be able to multiply the resulting number (php is weakly typed after all).
<?php
$number = str_replace("%", "", $percentString);
$newNumber = ((int) $number) * 1000;
echo $newNumber;
?>
You can use str_replace. You can also pass an array of subjects into str_replace to have them all replaced.
<?php
$number = str_replace("%", "", $percentage);
$result = $number * $other_var;
print $result;
?>
<?php
$input=array('15%','50%','10.99%','21.5%');
$multiplier=1000;
foreach($input as $n){
$z=floatval($n)*$multiplier;
print("$z<br>");
}
?>
Consider my variable $result to be 01212.... Now if i add 1 to my variable i get the answer 1213,but i want it to be 01213.... My php code is
echo sprintf('%02u', ($result+1));
Edit:
Answers to this question works.. But what happens if my variable is $result to be 0121212
in future...
You can use %05u instead on %02u
echo sprintf('%05u', ($result+1));
EDIT:
To generalize it:
<?php
$result = "0121211";
$len = strlen($result+1) + 1;
printf("%0${len}d", ($result+1)); // print 0121212
?>
you could try:
str_pad($result, 5, "0", STR_PAD_LEFT);
Maybe I'm missing something here but it could be as simple as
$result = '0'. ($result+1);
edit:
$test = array('01212', '0121212', '012121212121212', '-01212');
foreach( $test as $result ) {
$result = '0'.($result+1);
echo $result, "\n";
}
prints
01213
0121213
012121212121213
0-1211
( you see, there are limitations ;-) )
Read here: http://php.net/manual/en/function.sprintf.php
in sprintf, you also has to specify length you want - so in your case, if you want any number to be shown 5chars long, you haveto write
echo sprintf ('%05d', $d); // 5 places taking decimal
or even better
printf ('%05d', $d);
Seems like you want to have a '0' in front of the number, so here would be the simplest :P
echo '0'. $result;
Or if you insist on using sprintf:
$newresult = $result + 1;
echo sprintf('%0'.(strlen(strval($newresult))+1).'u', $newresult);