开发者

PHP convert string to array

开发者 https://www.devze.com 2023-01-08 01:58 出处:网络
How can I convert a string to an array? For instance, I have this strin开发者_开发百科g: $str = \'abcdef\';

How can I convert a string to an array? For instance, I have this strin开发者_开发百科g:

$str = 'abcdef';

And I want to get:

array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
}


Use str_split http://www.php.net/manual/en/function.str-split.php


You can loop through your string and return each character or a set of characters using substr in php. Below is a simple loop.

$str = 'abcdef';
$arr = Array();

for($i=0;$i<strlen($str);$i++){
    $arr[$i] = substr($str,$i,1);
}

/*
OUTPUT:
$arr[0] = 'a';
$arr[1] = 'b';
$arr[2] = 'c';
$arr[3] = 'd';
$arr[4] = 'e';
$arr[5] = 'f';
*/


Every String is an Array in PHP

So simply do

$str = 'abcdef';
echo $str[0].$str[1].$str[2]; // -> abc


Note that starting with php 5.5 you can refer to string characters by array indices, which in most cases prevents need for the solution(s) above.

$str = 'abdefg';
echo $str[4]; // output: f


Other solution:

$string = 'abcdef';

$arr = [];

for($i=0;$i<strlen($string);$i++){
    $arr[] = substr($string,$i,1);
}


<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
echo "<br/>";
print_r($arr2);

?>

more info !!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号