search
Homephp教程php手册字符串数组,删除数组元素

字符串数组,删除数组元素

Jun 13, 2016 am 10:24 AM
phppeopleelementdeleteFunctiondeal withstringrightarrayofKnowlanguage

字符串数组
  学过C语言的人可能都知道,C语言对字符串的处理功能很强,PHP是用C写成的,自然不例外的继承了C的处理字符串的优势。不过毕竟PHP是一门新的语言,与C语言还是有区别的,自然不能保证与C是完全相同的。所以有些功能只有经过测试才能知道。

  有时候需要对一个字符串的每个字符进行处理,一般的做法可能是:

$str="something";
for($i=0; $i{
$ch=substr($str, $i, 1);
//处理$ch
}

  这样是可以,但是有没有更优美一点的办法呢?有,就是把它看成一个数组,C语言就是这样处理的。

  我们把上面的例子,改成用字符串数组的处理方式:

$str="something";
for($i=0; $i{
$ch=$str[$i];
//处理$ch
}

  这样是不是好多了。

删除数组元素
  定义了一个数组,有时想删除其中几项怎么办?我在www.phpbuilder.com中看到了一个答案,就是使用unset()函数。还是让我们做一个测试吧。

$a[]="a1";
$a[]="a2";
$a[]="a3";
for($i=0; $i{
echo $a[$i] . "
";
}
unset($a[0]);
for($i=0; $i{
echo $a[$i] . "
";
}

  是什么意思呢?先生成一个有三个元素的数组$a,将其显示出来,然后,将第1个(下标为0)删除,再显示出来。结果应该是数组还剩两个元素了。但是不对呀!答案与我们想的不一样,难道是unset() 不好用吗?仔细想一想,原来unset($a[0])将第1个元素给删除了,但是输出时,我们还从$i=0 开始的,当然就不对了,php可不会自动调整下标的。这样只好用别的方法处理了:



$a[]="a1";
$a[]="a2";
$a[]="a3";
for($i=0; $i{
echo $a[$i] . "
";
}
unset($a[0]);
reset($a); //使数组指针回到第1个元素
while(list($c, $d)=each($a))
{
echo $d . "
"; //$c为数组下标
}

  这是一个通用的显示数组的方法,可以不用考虑数组的下标了。

  注意:sizeof()用于返回数组的个数,同count()一样。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools