weird float to int when moving a var - php

Here's my code, fetch_data.php returns a float (an exchange rate).
The first echo will return the float that I need (0.65 something) but the second one will return an integer (1)... Why? How do I fix this?
I'm using include because file_get_contents returned PHP for some reason? I don't have a lot of PHP experience and haven't written a line in a month so I'm rusty.
<div class="callout panel">
<p><strong>We sell for:</strong> $<?php
$coin_price = include('fetch_data.php');
$doge = $coin_price;
echo $coin_price;
echo $doge;
?> per 1000</p>
</div>
fetch data
$string = strip_tags($element); //<strong>$484.66</strong>
$string = str_replace('$', '', $string);
$int = $string;
$val = $int * 1.25;
echo $val / 1000;
any help appreciated

fetch_data.php
$string = strip_tags($element); //<strong>$484.66</strong>
$string = str_replace('$', '', $string);
$int = $string;
$val = $int * 1.25;
$coin_price = $val / 1000;
other php file
<div class="callout panel">
<p><strong>We sell for:</strong>
$<?php
include('fetch_data.php');
echo $coin_price;
$doge = $coin_price;
echo $doge;
?> per 1000</p>
</div>
I modified the code a bit if you want to use include like you are currently. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

You can use
$doge = floatval($coin_price);
Check here : http://www.php.net/manual/en/function.floatval.php

Related

Get range letter and number with php

how can I get range for bottom string in php?
M0000001:M0000100
I want result
M0000001
M0000002
M0000003
..
..
..
M0000100
this is what i do
<?php
$string = "M0000001:M0000100";
$explode = explode(":",$string );
$text_one = $explode[0];
$text_two = $explode[1];
$range = range($text_one,$text_two);
print_r($range);
?>
So can anyone help me with this?
This is one of many ways you could do this and this is a little verbose but hopefully it shows you some "steps" to take.
It doesn't check for the 1st number being bigger than the 2nd.
It doesn't check your Range strings start with a "M".
It doesn't have all of the required comments.
Those are things for you to consider and work out...
<?php
$string = "M00000045:M000099";
echo generate_range_from_string($string);
function generate_range_from_string($string) {
// First explode the two strings
$explode = explode(":", $string);
$text_one = $explode[0];
$text_two = $explode[1];
// Remove the Leading Alpha character
$range_one = str_replace('M', '', $text_one);
$range_two = str_replace('M', '', $text_two);
$padding_length = strlen($range_one);
// Build the output string
$output = '';
for ( $index = (int) $range_one; $index <= (int) $range_two; $index ++ ) {
$output .= 'M' . str_pad($index, $padding_length, '0', STR_PAD_LEFT) . '<br>';
}
return $output;
}
The output lists a String in the format you have specified in the question. So this is based solely upon that.
This could undergo a few more revisions to make it more function like, as I'm sure some folks will pick out!

PHP Convert money to string

I have a piece of code that is creating a progress bar on my page to show how much a user has spent out of an allotted amount.
$roof = 75
$total = 275.00 this works fine
$total = 1,202.00 this breaks because of the comma
<div class="progress">
<div class="progress-bar <?php if($total > $roof) { echo 'progress-bar-danger'; } ?>" role="progressbar" aria-valuenow="<?php echo $total ; ?>" aria-valuemin="0" aria-valuemax="<?php echo $roof ; ?>" style="width: <?php echo $total ; ?>%;">$<?php echo $total ; ?> of $<?php echo $roof ; ?> cap</div>
</div>
How can I get this to work correctly with higher dollar amounts that include these commas?
You should not do any logic with an already formatted string. Keep $total a clean integer or float and only add the decimal point and thousands separator on output.
PHP has the helpful number_format() function for this.
<?php
// Central function that is responsible to format currency
// values for display
function formatMoney($sum) {
$formattedString = number_format($sum, 2, "." , ",");
return $formattedString
}
$roof = 1000;
$total = 1202;
?>
<div>
<?php
// Format the number just for output:
echo formatMoney($total);
// $total remains a number:
if ($total > $roof) {
echo "warning";
}
?>
</div>
With this pattern, your business logic will be independent of how a currency value is displayed to the user. Otherwise you will be in trouble if you decide to change the number formatting later (e.g. when you add localization).
If you have no access to the unformatted value of $total you need to parse it back into a number:
// Remove thousands separator and parse into a Float value:
$total = floatval(str_replace(",", "", $formattedTotal));
Now you can use it as a number again and use it for things like $total > $roof.
Use echo number_format($total), you don't have to format it on your own.
One way:
$total = str_replace(',', '', $total);

PHP Array Looping & Exploding

I'm not very experienced in using PHP, but I'm having a hard time thinking of a way to do this. I'm reading from a file and exploding on ":" as you can see here.
<?php
$datainfo = file('data.txt');
for($i = 0; $i < count($datainfo); $i++){
$expdata = explode(':', $datainfo[$i]);
}
?>
The issue is that I need to reference specific indexes of the resulted explosion like this.
<p> <?php echo $expdata[1] ?> </p>
I'm getting back an array of the last line inside the data.txt file. I know why It's happening, I just don't know how to get what I want here. (Sorry Very New). Data.txt contain the following.
name:Octopod Juice Stand
balance:20
price:0.5
customers:12
starting:2014-05-26
end: 2014-09-01
juice:15.25
fruit:10
Change your code to
<?php
$datainfo = file('data.txt');
$expdata = array();
for($i = 0; $i < count($datainfo); $i++){
$expdata[] = explode(':', $datainfo[$i]);
}
?>
And then to get the first label.
<p><?php echo $expdata[0][0]; ?></p>
Or the first value
<p><?php echo $expdata[0][1]; ?></p>

split a string into two divs, and split inside the string php

I have a website on wordpress using ACF custom fields.
I have a custom field with around 100 lines of text.
a date and a text like this :
2003-01 PARIS RATP PHILIDOR
2003-01 BORDEAUX TRAMWAY
2003-02 ILE-DE-FRANCE ÉCOLE DES MINES
2003-05 PARIS CITROëN
2003-05 PARIS TRAVERSIÈRE
first of all I wanted to split the field (called "projets") in two separate divs, the first 50 lines in one div and the rest in another div :
here is the PHP code i'm using :
<div class="columns_projets_1">
<p><?php
$string = get_field('projets');
$array = explode("\n", $string);
for($i = 0; $i <50; $i++){
echo $array[$i];
}
?></p>
</div>
<div class="columns_projets_2">
<p><?php
$string = get_field('projets');
$array = explode("\n", $string);
for($i = 50; $i <count($array)-1; $i++){
echo $array[$i];
}
?></p>
</div>
It works perfectly !
but I would like for each line to get the date separatly for the text, to put the date in one div and the text in another one... like this :
<div class="date">2003-01</><div class="text">PARIS RATP PHILIDOR</div>
but I can't find how to code this, to have the first php code, and the next to split inside the line... I heard about substrings, I tried eveything but it's not working...
Can anybody help me ? would be really great !
I hope you can understand me !
thanks a lot
Mattieu
You can echo HTML too.
For instance:
for($i = 0; $i <50; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '<div class="date">'.$dateAndText[0].'</div>';
echo '<div class="text">'.$dateAndText[1].'</div>';
}
Although a cleaner way to do this would be something like this:
<?php for($i = 0; $i <50; $i++):
$dateAndText = explode(' ', $array[$i], 2); ?>
<div class="date"><?php echo $dateAndText[0]; ?></div>
<div class="text"><?php echo $dateAndText[1]; ?></div>
<?php endfor; ?>
Just use:
$test = explode(' ', $array[$i], 2);
$test[0] will be with the date, and in $test[1] you will have the rest of line.
For more information:
http://php.net/manual/pl/function.explode.php

Undefined index notice in php regexp

Well, I've tried searching over the internet for a few hours now, but so far it's been of no assistance. I am trying to figure out why I keep getting the following notice notice(yes, I am aware it is just a notice and does not halt the execution of the script):
Notice: Undefined index: 05 in [redacted_path]\script.php(31) : regexp code on line 1
This script was meant as a color re-placer for irc channel logs; I've grabbed the large function from another site and modified it slightly to suit my needs. Credit of course goes to its creator. That aside, I am.. lightly familiar with regex, but not the point where I can of course spot the offending typo or similar below. Any assistance would be appreciated.
<?php
if (isset($_POST['chn'])) {
$chn = $_POST['chn'];
$str = urldecode($_POST['line']);
$filen = "logs/$chn" . "_" . date('Y_F_d') . ".html";
$str = preg_replace('/https?:\/\/[^\s"<>]+/', '$0', $str);
$logln = mirc2html($str) . "<br />\r\n";
$logln = str_replace("Â","",$logln);
file_put_contents($filen,stripcslashes($logln),FILE_APPEND);
}
if (isset($_GET['test'])) {
echo str_replace("Â","",mirc2html($_GET['test']));
}
function mirc2html($x) {
$c = array("FFF","000","00007F","009000","FF0000","7F0000","9F009F","FF7F00","FFFF00","00F800","00908F","00FFFF","0000FF","FF00FF","7F7F7F","CFD0CF");
$x = preg_replace("/\x02(.*?)((?=\x02)\x02|$)/", "<b>$1</b>", $x);
$x = preg_replace("/\x1F(.*?)((?=\x1F)\x1F|$)/", "<u>$1</u>", $x);
$x = preg_replace("/\x1D(.*?)((?=\x1D)\x1D|$)/", "<i>$1</i>", $x);
$x = preg_replace("/\x03(\d\d?),(\d\d?)(.*?)(?(?=\x03)|$)/e", "'<span style=\"color: #'.\$c['$1'].'; background-color: #'.\$c['$2'].';\">$3</span>'", $x, -1, $n1);
$x = preg_replace("/\x03(\d\d?)(.*?)(?(?=\x03)|$)/e", "'</span><span style=\"color: #'.\$c['$1'].';\">$2</span>'", $x);
$x = preg_replace("/\x03|\x0F(.*?)/", "<span style=\"color: #000; background-color: #FFF;\">$1</span>", $x);
$x = str_replace("\n","",$x);
$x = str_replace("\r","",$x);
$x = preg_replace("/\<\/span\>/","",$x,1);
$x = preg_replace("/(\<\/span\>){2}/","</span>",$x);
return $x;
}
?>
The offending line is thus:
$x = preg_replace("/\x03(\d\d?)(.*?)(?(?=\x03)|$)/e", "'</span><span style=\"color: #'.\$c['$1'].';\">$2</span>'", $x);
The cause of your error is clear: The variable $c['05'] is not defined. Define it or change the replacement with a function that is able to convert it into an integer that - for some reason I'm not clear about - PHP is not able with that eval'ed regex replacement (normally numerical strings are converted into integer for keys automatically internally).
If you're open for some suggestions:
Refactor the code to remove the duplicate parts (It's always some code that does something, multiple classes of codes, each class has it's own replacements).
Do the replacement with a callback function so that you can better control the replacement and pass the color values.

Categories