PHP number_format returns 1.00 - php

I have stored in MySQL the number as total(decimal 16,2) 1423.28
I get it display from PHP after making some calculations:
function calculate_balance($total){
//get total paid from another function
$total_paid = ...
if ($total_paid == 0){
return $total;
}else{
return $total-$total_paid
}
}
$balance = calculate_balance($total);
echo number_format($balance, 2); //returns 1.00
I have tried
number_format((float)$balance, 2);
number_format(floatval($balance), 2);
UPDATE
var_dump($balance)
and I got following output.
string(8) "1,423.28" float(152) string(6) "252.00" string(6) "247.50" string(6) "247.50" string(6) "247.50" string(6) "549.90" string(6) "495.00" float(0) string(6) "284.76" float(265)
It's working fine without number_format() for value under 1,000.
E.g.: if balance equal 252.00
echo $balance;
output
252.00

Your function returns 1,423.28? This is not a float, as a float does never contain a comma as a thousands-separator.
PHP interprets this as 1, because it "breaks" at the comma.
Remove the comma and you are fine!
$balance = str_replace(',', '', $balance);

Following the answer of Lars Evert I used the function number_format like that
number_format($balance, 2, '.', '');
and that solved my problem

Related

4 bytes big-endian to int

I have a file that contains data (keywords) to interpret and starts with 4-bytes big endian to determine number of keywords. I can't seem to get the proper integer value from it.
$bytes = "00000103";
$keywords = preg_replace("/(.{2})(.{2})(.{2})(.{2})/u", "\x$1\x$2\x$3\x$4", $bytes);
var_dump($keywords);
$unpacked = unpack("N", $keywords);
var_dump($unpacked);
Outputs (incorrect):
string(16) "\x00\x00\x01\x03"
array(1) {
[1]=>
int(1551380528)
}
For testing purposes, I change the $keywords variable to:
$bytes = "\x00\x00\x01\x03";
It outputs (correct):
string(4) ""
array(1) {
[1]=>
int(259)
}
How do I change the data-type of $keywords? Searched a lot, but can't get it to work unfortunately.
PS. After posting, it doesn't show the 2 characters (boxes with questionmarks) in them in the correct output for string(4).
You can simply use the hexdec-function:
$bytes = "00000103";
$dec = hexdec($bytes);
var_dump($dec); //int(259)

Create specific patterns for a numeric range from given start and end numbers

I want to create a function which generates specific patterns to describe a numeric range between two given numbers. The function accepts two parameters: $startNumber and $endNumber. It should return an array of pattern strings. The best way to describe it is with examples:
myfunction(00000, 99999) = array('*');
myfunction(10000, 29999) = array('1*', '2*');
myfunction(68000, 68999) = array('68*');
myfunction(0004000, 0008999) = array('0004*', '0005*', '0006*', '0007*', '0008*');
myfunction(5570000, 5659999) = array('557*', '558*', '559*', '560*', '561*', '562*', '563*', '564*', '565*');
myfunction(3760000, 5259999) = array('376*', '377*', '378*', '379*', '38*', '39*', '4*', '50*', '51*', '520*', '521*', '522*', '523*', '524*', '525*');
myfunction(12345, 45678) = array('12345*', '12346*', '12347*', '12348*', '12349*', '1235*', '1236*', '1237*', '1238*', '1239*', '124*', '125*', '126*', '127*', '128*', '129*', '13*', '14*', '15*', '16*', '17*', '18*', '19*', '2*', '3*', '40*', '41*', '42*', '43*', '44*', '450*', '451*', '452*', '453*', '454*', '455*', '4560*', '4561*', '4562*', '4563*', '4564*', '4565*', '4566*', '45670*', '45671*', '45672*', '45673*', '45674*', '45675*', '45676*', '45677*', '45678*');
myfunction(000000, 399099) = array('0*', '1*', '2*', '30*', '31*', '32*', '33*', '34*', '35*', '36*', '37*', '38*', '390*', '391*', '392*', '393*', '394*', '395*', '396*', '397*', '398*', '3990*');
Since some parts of your issue are not clear,
I'll get closer to the first need you are claiming...
For the range
You don't need to recode the existing ;-)
Look for range() native function, can already do that for you:
function myfunction($start, $end)
{
$r = range($start, $end);
return array_map(function($n)
{
return $n.'*';
}, $r);
}
var_dump(myfunction(34, 39));
// will output:
array(6) {
[0]=>
string(3) "34*"
[1]=>
string(3) "35*"
[2]=>
string(3) "36*"
[3]=>
string(3) "37*"
[4]=>
string(3) "38*"
[5]=>
string(3) "39*"
}

PHP break string into two parts

Note: I can't use break or next line functions as i am using FPDF
I am having a problem with php strings. I am having a string where i want to show atmost 12 characters in first row and remaining in second row. So basically i want to break string into two parts and assign to two variables so that i can print those two variables. I have tried following code :-
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 12);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
But using this I am getting as shown below :
Original String : The Best Hotel Ever
Output :
The Best Hot
Tel Ever
It is breaking a word, i don't want to break the word, just check the length and if within 12 characters all the words are complete then print next word in next line. Like this :
Desired OutPut:
The Best
Hotel Ever
Any suggestions ?
I see no built-in function to do it, however you could explode on spaces, and re-build your string until the length with the next words get over 12, everything else going to the second part :
$string = 'The Best Hotel Ever';
$exp = explode(' ', $string);
if (strlen($exp[0]) < 12) {
$tmp = $exp[0];
$i = 1;
while (strlen($tmp . ' ' . $exp[$i]) < 12) {
$tmp .= " " . $exp[$i];
$i++;
}
$array[0] = $tmp;
while (isset($exp[$i])) {
$array[1] .= ' ' . $exp[$i];
$i++;
}
$array[1] = trim($array[1]);
} else {
$array[0] = '';
$array[1] = trim(implode (' ', $exp));
}
var_dump($array);
// Output : array(2) { [0]=> string(8) "The Best" [1]=> string(10) "Hotel Ever" }
// $string1 = 'The';
// array(2) { [0]=> string(3) "The" [1]=> string(0) "" }
// $string2 = 'Thebesthotelever';
// array(2) { [0]=> string(0) "" [1]=> string(16) "Thebesthotelever" }
Im not too crash hot on PHP but it seems to be a simple case of which element of the string you are accessing is futher across from where you want to be:
Try:
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 8);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
For further help check out because you need to remember to count from zero up:
http://php.net/manual/en/function.substr.php

php sort array and rank specific field

I am trying to output a ranking by lowest number first for a particular field (OurPrice) based on numeric values.
var_dump Result
$myarray = array_filter($rankresult);
natsort($myarray);
array(6) {
["Comp7"]=> string(3) "189"
["OurPrice"]=> string(3) "189"
["Comp9"]=> string(6) "198.99"
["Comp6"]=> string(3) "208"
["Comp3"]=> string(6) "226.97"
["Comp4"]=> string(3) "274"
}
You will notice that there are 6 total in the count and two of which are the same number, therefore it would equal the same rank (ie. Comp7 and OurPrice are both ranked 1 of 6).
Desired Output:
Our Price Rank = 1 of 6
try with this code
$newarray = (array_unique(array_values($myarray)));
$rank = array_search($myarray['OurPrice'],$newarray)+1;
$count = count($myarray));
echo "Our Price Rank" . $rank . " of " . $count"
Assuming you have already sorted the values (which it appears you have), you could simply tell them the index at which the "OurProduct" key exists.
$keys = array_keys( $array );
$rank = array_search( "OurPrice", $keys );
printf( "We rank %d of %d", ++$rank, count($keys) );
Try it online: http://codepad.org/qIwTGBzG

Split long string into little ones. - trying to find an elegant way for doing so

If the string is bigger then 50 chars long, I need to split it.
The maximum allowed is 3 chunks of 50. It could be less then 50 but never more then 150.
I don't need any special chars to be added, or to serve as "splitters"; I can break the string anywhere, no problem, since the propose is not for showing it to the user.
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
}
Is there a more elegant way for doing this?
UPDATE:
An example of what would arrive next:
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
if(!empty($streetPart2) && empty($streetPart3)
{
//add part2 only.
}elseif(!empty($streetPart2 && !empty($streetPart3))
{
//add part 2 and part 3
}
}
Thanks a lot.
MEM
You may simply use str_split:
$parts = str_split($string, 50);
// if you want to have vars instead of array:
list($part1, $part2, $part3) = str_split($string, 50);
Check the PHP's wordwrap() function.
http://php.net/manual/en/function.wordwrap.php
And check out the explode() function
http://php.net/manual/en/function.explode.php
<?
function wrapAndCropToArray($text, $width, $lines)
{
$ret = array_slice(
explode("\n",wordwrap($text,$width,"\n",true))
, 0
, $lines+1
);
if(isset($ret[$lines]))
$ret[$lines] = "...";
return $ret;
}
$test = "aadfuiosdy 34 123 412 341f2 38947 1029 384h120 39uh4 19023h 41234";
var_dump(wrapAndCropToArray($test,10,3));
?>
Will output:
array(4) {
[0]=>
string(10) "aadfuiosdy"
[1]=>
string(10) "34 123 412"
[2]=>
string(5) "341f2"
[3]=>
string(3) "..."
}

Categories