字符串到整数数组php [英] String to array of Integers php

查看:47
本文介绍了字符串到整数数组php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 php 中将字符串(例如 1、2、3、4、5、6)转换为整数数组?我发现只能访问字符串的第一个字符的函数,例如 1.如何将整个字符串转换为数组?

I wan to convert a string for example 1,2,3,4,5,6 to an array of integers in php? I find functions that only have access to the first character of the string for example 1. How can I conert the whole string to array?

function read_id_txt()
{

        $handle_file = fopen("temporalfile.txt", 'r'); 

        $i=0;

        while ($array_var[$i] = fgets($handle_file, 4096)) { 
            echo "<br>";
            print_r($array_var[i]);
            $i++;
        }

        fclose($handle_file);   

        $temp=explode(" ", $array_var[0]);      

        return $temp;   


}

推荐答案

使用 PHP 的 explode.

$str = "1,2,3,4,5,6";
$arr = explode("," $str); // array( '1', '2', '3', '4', '5', '6' );

foreach ($arr AS $index => $value)
    $arr[$index] = (int)$value; 

// casts each value to integer type -- array( 1, 2, 3, 4, 5, 6 );

根据 蒂姆·库珀的建议,使用 array_walk 比上面的循环更简单:

As suggested by Tim Cooper, using array_walk is simpler than the above loop:

array_walk($arr, 'intval');

这篇关于字符串到整数数组php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆