How to get CSV integers read as integers from a string variable - php

I have a string that I get from sanitizing some values from an xml file.
$resolutions=strip_tags($resolutions,allow); // gives me '75 75 300 300 600 600'
Then I change the spaces to commas:
$resolutions = preg_replace('#\s+#',',',trim($resolutions)); // gives me '75,75,300,300,600,600'
Then I take that and want to extract min and max values like this
$resolution_min = min($resolutions);
on the page for display
echo $resolution_min; // still gives me '75,75,300,300,600,600'
However when I change the code where I want it displayed on the page
echo min(75,75,300,300,600,600); // it displays '75' as it should
I think, the issue is that the CSV values are being interpreted as a single text string and I need them read as CSV integer values.
Is there some way to force these to be read as numeric values by min and max?
I think part of my problem comes from this line or a line like it, jus befor an "explode" command
$list = "" . substr($scansupportedresolutions, $start,$length) . "";
I have never seen this kind of double double quote dot and dot double double quote and have no idea what it means
Is it simply saying the entire string in $list will be
".<CONTENT HERE>."
but specifically in double quotes? Whatever it is i seems crucial to the explode command.

From min:
If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.
You are passing one parameter and it's a string. Pass an array:
$resolutions = explode(',', $resolutions);
$resolution_min = min($resolutions);

AbraCadaver is correct in his answer.
I have tried to improve your code. Take a look
<?php
// After Stripping tag
$resolutions = "75 75 300 300 600 600";
// No need to conver to Space to comma
$resolutionsArray = explode(" ", $resolutions);
$resolutionMin = min($resolutionsArray);
print($resolutionMin);
There is no gain by converting the "white Space" to "Comma". You can explode the string into array by setting "white Space" as delimiter.
Hope it helps you.

Related

WooCommerce : How to convert wp_price value to a numeric value?

I'm developing a table with two columns, "State" and "Sales". To get the number in the sales column, I use the wc_price function, which works just fine to output a currency string:
CA $1,652.13
CO $515.80
...etc.
I have at least 50 rows, one for each state.
The very last row will output the total of all the dollar amounts from column 2.
I discovered that the actual result from wc_price isn't just a sting, it's a block of html:
<bdi>
<span class="woocommerce-Price-currencySymbol">$</span>
435.50
</bdi>
I tried to get to the actual number within the html, 435.50 using strip_tags:
$numeric = strip_tags(wc_price($total)); // result is a simple string, with the $ sign
echo str_replace("$","",$numeric) . "<br>"; // doesn't strip away the $ sign.
$tally = $tally + $numeric; // produces an error, non-numeric value.
The error is on the $tally = line. This doesn't work in any way. Sure, the html tags are stripped, and I'm left with a string: $435.50. In other words, I can't get rid of that danged '$' for some reason. I simply cannot parse, convert, or anything to that currency string. (int), intval($numeric), (float)$numeric, floatval($numeric), etc., none of these work. number_format doesn't work, either.
Warning: A non-numeric value encountered in C:\xampp\htdocs\mysite\wp-content\plugins\my-custom-plugin\my-custom-plugin.php on line 104
Add a floatval() around your str_replace and assign the variable.
$numeric = strip_tags($html);
$numeric = floatval(str_replace("$", "", $numeric));
See working example. It works with 5.6, 7.4 and 8.1.
I'm not sure of the result, but I think it's possible to have the price without the currecy reading from the documentation of wp_price:
$numeric = wp_price($total, array('currency'=>''));
However you can have some action that change the comportament of the wc_price function.

convert string into sequential array in php

I want to convert this string: ["5b09e23972929.png", "5b0a7f1361a00.png"] that I get from my MySQL database into an sequential array. The reason is I want to remove single parts of the string. So $string[0] should have the value 5b09e23972929.png is this case.
$result = json_decode('["5b09e23972929.png", "5b0a7f1361a00.png"]');

Update a string to follow a specific format

I have a column in my database that stores a string of numbers, separated by commas.
,,133,,,,444,,,,555,,,,6,
Rules:
The first number in the string is always preceded by 2 commas
There are always 4 commas between the middle numbers
The last number only has 1 comma after it
The example above is how I always want the string to look..
What happens is when some of these numbers are removed the updated string looks like this:
,,31,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,998,,,,476,,,,,
Making it look messy in the database and sometimes causing trouble with the extra commas when I try to output each number
I've been manually updating each value to follow the format I want but I'd like to make a script that runs each night and takes each of these strings and updates them with the correct format following the rules I listed above.
What can I use to format the string to follow the rules above?
You could create a php script that loads the values from the database, manipulate the rows, and store the manipulated values back to the database. I don't know what database and table structure you use, but the manipulation part is simple:
// load the string from the database into the $value variable
$numbers= preg_split("/,+/", $value); // split the string
$numbers= array_filter( $numbers); // remove empty array elements
$newvalue = implode(',,,,', $numbers); // join the array elements to a string separated by ,,,,
$newvalue = ',,' . $newvalue . ','; // add ,, at the beginning and , at the end of the new value
// store $newvalue in the database

PHP - Parsing results are not consistent

Parsing a string value to a float value is not consistent in my PHP project. Altough I'm not changing my code and the values to parse are always the same I sometimes get a result with a comma and sometimes with a point.
The incoming value is for example: 35,59
Before parsing this value I first replace the comma by a point.
$value = '35,59';
$value = (float)str_replace(',', '.', $value);
var_dump($value);
When I now use this value in my insert query, this sometimes results in a bug because a comma is used.
This is all a bit weird to me, has anyone experienced this before? How can I prevent this from happening?
Edit:
I indeed forgot my quotes in this example, but I did use quotes in my code
$value = 35,59;
The problem is that the parser cannot recognize "," as a decimal delimiter. Your locale may define numbers this way but programmatically you must use periods or declare the value as a string.
$value = "35,59";
// or
$value = 35.59;
If you get 35,59, that must be hard-coded since any data-source returning this value is automatically treated as a string.
See http://us2.php.net/numberformatter.parse for information on how to cast the formatted string correctly.
I.e
$fmt = new NumberFormatter( 'sv_SE', NumberFormatter::DECIMAL );
$value = "35,59";
echo $fmt->parse($value); // 35.59
Edit
Also your str_replace will fail for X number of locales since some usually use "," as a thousand separator.

Most efficient PHP str_replace on array if row only has 5% chance of containing target?

I have a 15,000 row PHP array. I need to iterate through each row to generate a 15,000 row Javascript array. Each row of the PHP array has a 5% chance of containing one or more HTML special characters like &#243; that I need to replace with the equivalent javascript hex. There are about 50 HTML special characters I have to look out for and replace, so I'd use str_replace(array_of_HTML_targets, array_of_hex_replacements, haystack). Is it more efficient to:
Go through each line of the PHP array, search for an ampersand, and if one exists do the search and replace (considering this will apply for only 5% of the rows)
Execute the search and replace on the entire array
Concatenate the array into one giant string and execute the search and replace on the giant string
Other idea? Please specify
Btw, reason for 15,000 PHP array is this is a data visualization app.
Since you already need to dump your PHP data into a string (probably JSON), you might as well work on the final string, like so:
$json = json_encode($your_php_array);
$unhtmlref = preg_replace_callback("/&#(x[0-9a-f]+|\d+);/",function($m) {
if( $m[1][0] == "x") $m[1] = substr($m[1],1);
else $m[1] = dechex($m[1]);
return sprintf("\\u%04s",$m[1]);
},$json);
This is safe, because HTML character codes don't have any special meaning in a JSON string.
That said, I have a function in my JavaScript "utility belt" that does something similar:
function unHTMLref(str) {
// take a string and return it, with all HTML character codes parsed
var div = document.createElement('div');
div.innerHTML = str.replace(/</g,"<");
return div.firstChild.nodeValue;
}
So basically you can either parse before, or after. Personally, I'd prefer "after" because it shifts some of the "grunt" work to the browser, allowing the server to do more important things.

Categories