I wrote this function that takes a number and formats it with commas, so every three digits from right-to-left, a comma as added.
It works, but there is this error of "unitialized string offset" which I found was due to me treating the string as an array.
I decided to post my code to also see if there was a more straight forward way to do this.
Otherwise, my main question is how can I turn that string into an array?
I tried to use str_split but it broke my code/page.
<?php
// comma function
function commaCreate($num) {
// convert number to string
$int_string = strval($num);
// turn $int_string into an array (omitted as it doesn't work)
// $int_string = str_split($int_string);
// get length of string
$int_length = strlen($int_string);
// create variables
$counter = 0;
$formatted_number = "";
// run through number right-to-left
for ($i = $int_length; $i >= 0; $i--) {
if ($counter == 3) {
// add number
$formatted_number = $int_string[$i].$formatted_number;
// add comma
if ($i != 0) {
$formatted_number = ",".$formatted_number;
}
// reset counter
$counter = 0;
$counter++;
}
else {
$formatted_number = $int_string[$i].$formatted_number;
$counter++;
}
}
// output formatted number
echo $formatted_number;
}
commaCreate(300000); // outputs 300,000
?>
I think I just realized what I could have done had I chosen to pursue this route.
I'd just go through the string (as an array cringe) and add it to an array.
something like
$array = array();
$num_string = strval($num);
$num_length = strlen($num_string);
for ( $i = 0; $i < $num_length; $i++) {
$array = $num_string[$i];
}
I think that would work, not sure, would have to try it, but I have a solution that's much simpler already thanks to akDeveloper
PHP "$" variables include every type of variables. You just need some tricks to convert any variable to what you want. For example:
$n = 12345; // This is integer
$s = $n.""; // Now $s is string.
echo $s[2]; // Now $s is array.
OUTPUT: "3". as $n at 2 = 3