Home  >  Article  >  Backend Development  >  字符串便是数组吗

字符串便是数组吗

WBOY
WBOYOriginal
2016-06-13 12:10:001150browse

字符串就是数组吗
下面这 段代码中$str也没有事先声明为数组,上来就写成数组的样式,这样写是不是太牵强了,因为字符串怎么能是数组呢,要是也行,可事先要声明啊,那么问题来了,这到底是为什么

$str="1234567890";<br />$s='';<br /><br />for($i=0;$i<4;$i++)<br />{<br />    $k=mt_rand(1, strlen($str));<br />    $s.=$str[$k-1];<br />}

------解决思路----------------------
字符串和数组是不同类型,字符串可以以数组形式访问。你这个例子,$str[$k-1] 是 substr($str, $k-1, 1)的简写,所以可以使用。

但如果是下面这个例子,就不行,所以用合适的类型很重要。
<br />$str="1234567890";<br />$str1="abcdefg";<br />$result = array_diff($str,$str1); // 出错<br />print_r($result);<br /><br />$str=array('1','2','3','4','5','6','7','8','9','0');<br />$str1=array('a','b','c','d','e','f','g');<br />$result = array_diff($str,$str1); // 正常<br />print_r($result);<br />

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn