Return string with leading zeros in PHP - php

Similar to this unsolved question
My PHP output requires JSON_NUMERIC_CHECK enabled, however there is one string nick column in my database that needs to be returned originally as a string. Values in that column can contain numbers and there's no length restriction. Code example:
$response["players"] = array();
...
$stmt = $connection->prepare('SELECT id, nick FROM players WHERE NOT id = ? ORDER BY nick');
$stmt->bind_param('i', $_POST["id"]);
$stmt->execute();
$result = $stmt->bind_result($id, $nick);
while ($stmt->fetch()) {
$players = array();
$players["id"] = $id;
$players["nick"] = $nick;
array_push($response["players"], $players);
}
...
echo json_encode($response, JSON_NUMERIC_CHECK);
For example, nick "007" is being returned as "7" and I need it to be the original "007". Removing "JSON_NUMERIC_CHECK" helps, but it bugs the rest of the code. Strval() function used like quoted below didn't help.
$result = $stmt->bind_result($id, strval($nick));
$players["nick"] = strval($nick);

In PHP there is unfortunately no explicit type for variables, this makes your problem not so easy to solve.
I came with 2 solution.
1) if you like OOP, make a Serializable, Arrayable class to use as container for your string with a method returning the right encoded value.
2) first encode using JSON_NUMERIC_CHECK in order to make sure your data is what you expect it is, then decode the validated data, manually set the string to its origina value, then encode again but this time not using JSON_NUMERIC_CHECK.
$str = $response['nick'];
$response = json_decode(json_encode( $response, JSON_NUMERIC_CHECK ) );
$response->nick = $str;
$response = json_encode( $response );

The management of numbers is strange to say the least ...
It's almost scary !
then on PHPTESTER:
$CUSTOMER['id'] = 123;
$CUSTOMER['tel'] = '06 06 06 06 06';
// unbug for zero top of tel number -> json_encode
$CUSTOMER['tel'] = "".$CUSTOMER['tel']."";
echo json_encode($CUSTOMER, JSON_NUMERIC_CHECK);
Output : {"id":123,"tel":"06 06 06 06 06"}
On my host (same code) : Output : {"id":123,"tel":"6 06 06 06 06"} // zero was removed !
I found an unlikely solution :
I surrounded the variable with a space ...
$CUSTOMER['tel'] = " ".$CUSTOMER['tel']." "; // wrap with spaces
Output (on my host) : {"id":123,"tel":"06 06 06 06 06"}
in PHP version 5.5
Here is a solution, I would like to have your opinion, in any case it worked for me.

Related

Trying to convert letters into numbers

So I've created a function to allow letters single letters to be changed in to a 2 digit number.
This is the code:
<?php
function Letter2number($abc) {
//A = 00
str_replace('a','00',$abc);
str_replace('A','00',$abc);
//B = 01
str_replace('b','01',$abc);
str_replace('B','01',$abc);
//C = 02
str_replace('c','02',$abc);
str_replace('C','02',$abc);
//D = 03
str_replace('d','03',$abc);
str_replace('D','03',$abc);
//E = 04
str_replace('e','04',$abc);
str_replace('E','04',$abc);
//F = 05
str_replace('f','05',$abc);
str_replace('F','05',$abc);
}
?>
When the variable from a form input is processed though this function it was meant to output a 2 digit number.
But the output is blank.
Any idea what I'm doing wrong?
First attempt at programming? I hope you have a bit of fun. There are two major problems with your code, both have to do with return values.
Something like str_replace('F','05',$abc); returns a string, which you have to do something with. For instance: $abc = str_replace('F','05',$abc);.
Your function doesn't return anything. At the bottom of the function use return $abc;.
Also consider your choice of variable name: $abc implies that it contains the alfabet, not one letter. A better name would be $letter.
TIP: I used $abc in the above points to not confuse you any further, but the code itself is far from optimal. Can you make it better?

How to get measument name out of a string in PHP

I have a feed in array form which contains area of construction
$x['AC']="25";
sometime it comes with the measurement value attached in the string itself
$x['AC']="25mt2"; or $x['AC']="25 mt2"; or $x['AC']="25m2";
$x['AC']="25ht2"; or $x['AC']="25 ht2"; or $x['AC']="25h2";
how can I detect this and then clean the value of the array to just number .
and once its detected I have to create a string like
mt2[;;;]25 or ht2[;;;]25
Thanks in advance
I would use a preg to remove other caracters than numbers:
$x['AC'] = preg_replace('/\D+/','',$x['AC']);
But would leave any additional value besides the 25 that you refer, but if 25 is the first number, i would use a preg to get the first numbers in the string:
if(!is_numeric($x['AC'])){
preg_match('/^\d+/',$x['AC'],$nr);
$x['AC'] = $nr[0];
}
To get the inside mt or ht also, i would modify the regex like:
if(!is_numeric($x['AC'])){
preg_match('/^(\d+)\s?(.*)$/',$x['AC'],$nr);
$x['AC'] = $nr[1];
$mtORht = $nr[2];
}
OK, resuming, so m2 is default, and for anything else you wish to create a variable with that value in array:
OK, float values too:
if(!is_numeric($x['AC'])){
preg_match('/^([0-9\.]+)\s?(.*)$/',$x['AC'],$nr); //$x['AC']="25 ht2"
$theValue = $nr[1]; //25
$theMeasurementName = $nr[2]; //ht2
//creating the variable:
if(!stristr($theMeasurementName, 'm')){ // if no "m" is found, the m you wish to omit.
${$theMeasurementName} = $theValue; // $ht2[] = 25
}
}
You can just cast it to an integer and if there is a non numerical value it will get cut off, like this:
$x['AC'] = (int) $x['AC'];
example input/output:
25 -> 25
25mt2 -> 25
25ht2 -> 25
25 mt2 -> 25
25 ht2 -> 25
25m2 -> 25
25h2 -> 25
EDIT:
As per your updated question you can use preg_match() to create your string:
preg_match("/^(\d+)\s*(.*?)$/", $x["AC"], $m);
echo (empty($m[2])?"m2":$m[2]) . "[;;;;]" . $m[1];
$match = array();
preg_match('/^\d+/', $string, $match));
echo $match[0];
Regex:
^ -> begin with
\d+ -> any digit repeated

Array size in PHP shown as one despite of having more elements

Following is my code which I am using for testing purposes so far. I have to use it further in my project.
It access a certain web service and retrieves data as xml. XML is brought to $arr array.
Address of $url and 3rd parameter in client->call() are not mentioned on purpose.
$url = "";
$client= new nusoap_client($url);
$param = array("status"=>"p2");
$arr = $client->call('getAllVisitByStatus',$param,'');
echo $arr."\n";
$size = sizeof($arr);
echo $size;
for($num=0; $num<986; ++$num)
{
echo $arr[$num], "\n";
if($arr[$num] == '>')
{
echo "<br/> ";
}
}
If I save the data returned by client->call() into an array and print it with a loop then it prints the XML like this
<?xml version = "1.0" encoding = "UTF - 8" standalone = "yes" ?>
<lists>
<visitW>
<followup> 2015 - 01 - 30 00:50:00.0 </followup>
<person_id> 12 </person_id>
<remarks> nothing </remarks>
<treatment> doing </treatment>
<visit_date> 2015 - 01 - 04 - 00 - 24 - </visit_date>
<visit_id> 4 </visit_id>
<visit_type> Hesschart</visit_type>
</visitW>
</lists>
However, if take $arr as a string, it prints this:
2015-01-30 00:50:00.0 12 nothing doing 2015-01-04-00-24- 4 Hesschart
So, in a string it prints without tags and like this.
The problem is that when the size of array is printed, it prints 1. However, the array contains the whole XML brought as a result of service call.
When I use a loop of exact number of elements i.e. 986, then it prints the whole XML as it is.
The question is that why does it show 1 as the size of the array? Also, can this array containing XML be put in DOM Parser?

Evaluating php code stored in database

I have several strings stored in a database (yes, I know it's not the best practice, but I'm working with a system someone else designed and I cannot change it.)
For example, in my table called specialDates, I have a computedDate column that contains this:
date('d', strtotime("thursday, november ".date("Y")." + 3 weeks"))
This is pulled into my code and stored in a variable called $request['order_date'].
This, when used in standard PHP code, returns the date that Thanksgiving falls on in the current year. I need to pass the evaluated value of this (for this year - 2013 - the value is 28) to another query. But I can't seem to get the value to evaluate.
$query = 'SELECT count(orderID) as numberOfOrders FROM customer_orders WHERE customerID = ? AND orderDate = ?';
$param = array($request['customer_id'], eval($request['order_date']));
doesn't work. And when I just try to echo out the value to the screen, doing this:
echo eval($request['order_date']);
or this:
echo eval(" return \$request['order_date']; ");
just prints out the literal value of the string (i.e. date('d' etc.) rather than the expected evaluated value.
What am I doing wrong?
UPDATED
I tried AScherer's answer below, and although it does work when I just echo the value to the screen:
echo eval(" return {$request['order_date']}; ");
it does not work when I try to use the eval inside my array:
$param = array($request['customer_id'], eval("return {$request['order_date']}"));
How can I get this working so that the value I'm passing in the array is the actual value of 28, rather than the string pre-eval?
You were escaping the $request in your return part, which you dont want to do. This method should work, but id suggest adding return the the row in the database so u dont have to modify the eval
$sql = "SELECT customer_id, CONCAT( 'return ', order_date, ';' ) as function from customer_orders WHERE customerID = ? AND orderDate = ?";
$param = array( $request[ 'customer_id' ], eval( $request[ 'function '] ) );
---
OR
---
$evalData = eval(" return {$request['order_date']}; ");
$param = array($request['customer_id'], $evalData );
Yes, you can change it. If not to a sensible result, then to a useful result nontheless.
Your input data is a string:
date('d', strtotime("thursday, november ".date("Y")." + 3 weeks"))
This is an information to "calculate Thanksgiving of this year". You can set up a lookup table that detects this string and the needed function to execute:
$dateCalculations = array(
'date(\'d\', strtotime("thursday, november ".date("Y")." + 3 weeks"))' => function()
{
return date('d', strtotime("thursday, november ".date("Y")." + 3 weeks"));
}
'date(\'...whatever else is in the system...' => function(){}
// alias names also work
'thanksgiving' => function()
{
return date('d', strtotime("thursday, november ".date("Y")." + 3 weeks"));
}
);
You can then try to find the string from the database in the array and instantly have the function you need to call:
$thanksgiving = $dateCalculations[$dbvalue]();
From here you can go anywhere. Note that this will also work with the alias name "thanksgiving", so you might be able to replace it in the database if you know where else this braindead approach is also used... If not, at least you tried your best.

How to convert some character into numeric in php?

I need help to change a character in php.
I got some code from the web:
char dest='a';
int conv=(int)dest;
Can I use this code to convert a character into numeric? Or do you have any ideas?
I just want to show the result as a decimal number:
if null == 0
if A == 1
Use ord() to return the ascii value. Subtract 96 to return a number where a=1, b=2....
Upper and lower case letters have different ASCII values, so if you want to handle them the same, you can use strtolower() to convert upper case to lower case.
To handle the NULL case, simply use if($dest). This will be true if $dest is something other than NULL or 0.
PHP is a loosely typed language, so there is no need to declare the types. So char dest='a'; is incorrect. Variables have $ prefix in PHP and no type declaration, so it should be $dest = 'a';.
Live Example
<?php
function toNumber($dest)
{
if ($dest)
return ord(strtolower($dest)) - 96;
else
return 0;
}
// Let's test the function...
echo toNumber(NULL) . " ";
echo toNumber('a') . " ";
echo toNumber('B') . " ";
echo toNumber('c');
// Output is:
// 0 1 2 3
?>
PS:
You can look at the ASCII values here.
It does indeed work as in the sample, except that you should be using php syntax (and as a sidenote: the language that code you found most probably was, it did not do the same thing).
So:
$in = "123";
$out = (int)$in;
Afterwards the following will be true:
$out === 123
This may help you:
http://www.php.net/manual/en/function.ord.php
So, if you need the ASCII code you will need to do:
$dest = 'a';
$conv = ord($dest);
If you want something like:
a == 1
b == 2
.
.
.
you should do:
$dest = 'a';
$conv = ord($dest)-96;
For more info on the ASCII codes: http://www.asciitable.com/
And for the function ord: http://www.php.net/manual/en/function.ord.php
It's very hard to answer because it's not a real question but just a little bit of it.
But if you ask.
It seems you need some translation table, that defines links between letters and numbers
A -> 2
B -> 3
C -> 4
S -> 1
or whatever.
You can achieve this by using an array, where keys would be these letters and values - desired numbers.
$defects_arr = array(
'A' -> 2,
'B' -> 3,
'C' -> 4'
'S' -> 1
};
Thus, you can convert these letters to numbers
$letter = 'A';
$number = $defects_arr($letter);
echo $number; // outputs 1
But it still seems is not what you want.
Do these defect types have any verbose equivalents? If so, why not to use them instead of letters?
Telling the whole story instead of little bit of it will help you to avoid mistakes and will save a ton of time, both yours and those who to answer.
Out of this question, if you are looking for convert RT0005 to 5
$max = 'RT0005';
return base_convert($max,10,10);
// return 5

Categories