douzhiba6873 2016-08-12 17:36
浏览 85

将php整数转换为字符串到数组?

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

  • 写回答

1条回答 默认 最新

  • doucong4535 2016-08-12 18:41
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!