This php string joining is driving me crazy! - php

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.

Related

Count how many numbers and letters in the variable using PHP

I'd like to count how many numbers and letters are in the variable using PHP. Below if my code:
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
echo 'END UNIT: '.substr_count($lot_num, 'E').'<br />';
the code will count how many letter E are there in my lot_num variable but i would also like to count how many numbers are in the variable. Supposed, E1 and E18 should not be included when counting numbers.
I hope you can help me guys.
Try this: explode on , to get array that can be counted.
https://3v4l.org/r6OKl
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$ecount = substr_count($lot_num, 'E');
$totcount = count(explode(",", $lot_num));
echo 'END UNIT: '.$ecount;
Echo "\ntotal count: ". $totcount;
Echo "\nother count: ". Intval($totcount-$ecount);
No loops and no regex makes it a simple and quick solution.
You could always turn it into an array and use a loop:
$lot_num = explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$count = 0;
for ($i=0;$i<count($lot_num);$i++) {
if (is_int($lot_num[$i])) { //detects all numbers
$count++;
}
}
echo $count;
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$array = explode(',', $lot_num);
$data=array();
foreach($array as $k=>$val){
if(is_numeric($val )){
$data['number'][] = $val;
}else{
$data['string'][] = $val;
}
}
echo count($data['number']);
echo count($data['string']);
you can use is_numeric() and
if (!preg_match("/^[a-zA-Z]$/", $param)) {
// throw an Exception...
}
inside a loop
Id use preg_match
preg_match('/\b([0-9]+)\b/', $lot_num, $matches );
And matches would be like this.
$mathes[1][1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18]
So you would
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$total = 0;
if( preg_match('/\b([0-9]+)\b/', $lot_num, $matches )){
$total = count( $mathes[1] );
}
You can see how the Regx works here https://regex101.com/r/17psAQ/1
1,first u have to seperate the string and stored into array
2,then u can easily count the value of integers
<?php
$lot_num =explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18'));//seperate string by ","
$arr_count=count($lot_num);
for($i=0;$i<$arr_count;$i++)
{
$get_num[]=$lot_num[$i];//saving seperated string value into array
}
$count=0;
for($j=0;$j<count($get_num);$j++)
{
if(is_numeric($get_num[$j]))//chect whether the value is integer or not
{
$count++;
}
}
echo $count;

Tidy up PHP echo code [duplicate]

This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Closed 5 years ago.
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
echo $arr[11];
echo $arr[12];
echo $arr[13];
echo $arr[14];
echo $arr[15];
echo $arr[16];
} else {
echo 'No';
}
?>
Thanks in advance.
The code you posted probably has bugs, because the way it's written, it looks like it's intended to do something different from what it is actually going to do.
str_split() will take a string and output an array of single characters. It looks like you're trying to pass it two parameters, but enclosing them in quotes means it's actually just a single string.
Thus, if $url is equal to abc, your str_split() call will output an array of a, b, c, ,, , P, H, P, _, U, R, L, _ ... etc.
I don't think that's what you intended.
However, if it is what you intended, then you are splitting the string, only to re-join some of the characters back together again with echo. You can therefore can simplify the whole thing as follows:
$url = get_field('bothscoreno');
if ($url) {
echo substr($url, 11, 6);
} else {
echo "No.";
}
If I'm right and this isn't what you actually want to do, then I suggest either editing the question to clarify or asking a whole new one.
use for loop and start index from 14 to echo your result
$values = get_field('bothscoreno');
$url = $values;
$arr = str_split("$url, PHP_URL_QUERY");
$string = '';
if ($url) {
for($i = 11;$i <= 16;$i++){
$string .= $arr[$i];
}
} else {
$string = 'No';
}
echo $string;
Use the point as concatenation operator
echo $arr[11].$arr[12]
in PHP you're able to use a . as concatenation operator.
See the code below:
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
echo $arr[11].
$arr[12].
$arr[13].
$arr[14].
$arr[15].
$arr[16];
} else {
echo 'No';
}
Hope this helps!
Use array_slice
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
$subArr = array_slice($arr, 11, 6);
print_r($subArr);
// Or...
foreach ($subArr as $val) {
echo $val;
}
} else {
echo 'No';
}
?>

Deleting part of variable String in php

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

Trouble with PHP if else logic and variables

So, I have a couple of variables in PHP, and they are generated from different places. $new_ip comes from the following command:
$new_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');
And the $old_ip comes from:
$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];
My problem is, I am getting incorrect results from:
if ($old = $new)
{
$different = '1';
}
else {
$different = '2';
}
echo $different;
I ALWAYS get 2, wether the IPs are the same or not; if I use '==' as the comparison, I ALWAYS get 1.
When I run the following code, I get the following output:
var_dump($old_ip);
var_dump($new_ip);
Output
string(15) "123.123.123.123" string(167) "184.6.216.163 "
Are the variables different types? If So, can I make them the same so I am only comparing the IP and not the type? If the IPs are the same I should get '1' and if they are different, I should get '2', right?
Your problem is lurking here:
string(15) "123.123.123.123" string(167) "184.6.216.163 "
^^^
The address retrieved from your database is coming along with 154 unwanted characters. trim() both strings and then do the comparison.
Oh - and you should really shorten the field that stores the IP address. 15 characters should do.
Code
if ($old = $new) // you are using assignment operator here
{
$different = '1';
}
Should be
if ($old == $new) //Equal to operator
{
$different = '1';
}
Also confirm the variable names are
$old and $new or $old_ip and $new_ip
Assignment ( = ): Assigns the value on the right to the variable on the left
Equality ( == ): Checks if the left and right values are equal
Identical ( === ): Checks if the left and right values are equal AND identical (same variable type)
Example:
$a = 1; // Sets the value of $a as the integer 1
$b = TRUE; // Sets the value of $b to the boolean TRUE
if ($a == $b){
echo 'a is equal to b.';
}
if ($a === $b){ // compare VALUE and data type: if $a(integer) === $b(boolean)
echo 'a is identical and equal to b.';
}
if ($a = $b){
echo '$b value to variable $a';
}
In your code i noticed a problem. A space is there in second IP address. so
string(15) "123.123.123.123" string(167) "184.6.216.163 "
^
Trim both IP address.
If not work, then convert it to other datatype and compare.(Just for debugging purpose. :))
OLD :
if ($old = $new){
$different = '1';
}
New Correct :
if ($old == $new){
$different = '1';
}
you are using (=) assignment operation in the place of comparison operation.
As far as I can see the behaviour is normal because you are using $old and $new both are unset.
$new_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');
$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];
The next code will always give 2 because $new is unset. What you are doing here is assigning $old the value of $new and since $new is unset $old = $new will always be false.
if ($old = $new)
{
$different = '1';
} else {
$different = '2';
}
echo $different;
In the next example you are actually comparing $old and $new. Since both are unset the expression $old == $new will always be true.
if ($old == $new)
{
$different = '1';
} else {
$different = '2';
}
echo $different;
What you need to do is using the right vars and trim them.
// get new ip and trim white spaces
$new_ip = trim(file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php'));
// get the old ip
$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];
if ($old_ip == $new_ip)
{
$different = '1';
} else {
$different = '2';
}
echo $different;
I am not trimming white spaces on $old_ip because I guess that you will be using $new_ip to update your database and since $new_ip is already trimmed we can be sure that $old_ip has no white spaces.
You should always have php warnings enabled when coding!
It would have popped you a warning because you used unset vars.
PS : note that this code will only work as expected if file_get_contents() returns a IP with white spaces, the output could be different (error output, not able to detect ip correctly, ... etc)

str to float problems; what am i doing wrong?

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

Categories