浅谈PHP中foreach/in_array的使用_PHP
php在开发效率很高,这是无可厚非的,但是却是在牺牲执行效率的。php数组功能非常强大,但是也要多加考虑,多试几种情况情况,以防万一,这里,我就简单的说两个遇到的坑,以后如果有发现更多的,再补上吧!
foreach 提供了遍历数组的简单方式,可以很方便的读取到数据或对象的内容,但是官方文档说了,由于 foreach 依赖内部数组指针,在循环中修改其值将可能导致意外的行为。所以,基本上,
1、不要想在循环内部修改里面的值,否则结果将超出你想要的;
2、使用'&'是一个安全的方式,虽然很少用到,但是在用到时,在引用结束后,应立即调用unset函数销毁该变量,否则,在接下来的代码里,如果有再次使用到此变量,那么循环的最后一次值就将被修改了,从而得到了意外的值,比如:在列表循环输出时,最后一行输出将会出现许多乱七八糟的值或者空值。使用unset可解决此问题。
我们来看个示例
<?php /*-------------------------------------------------------------------------*/ /* foreach example 1: value only */ echo "foreach example 1: value only ".'<br />'; $a = array(1, 2, 3, 17); foreach ($a as $v) { echo "Current value of ".$a.":". $v."<br />"; } ?> // 运行结果 foreach example 1: value only Current value of $a: 1 Current value of $a: 2 Current value of $a: 3 Current value of $a: 17
in_array,其含义是检查前一个字符串是否存在于后一个数组当中,而且大多数情况下,它也是这么工作的,但是当后面的数组是整数时,如array(0,1,2,3)时,就出问题了,php会将前的字符串进行intval,从而都会得到0这个值,那么如果恰巧,你的数组当中有这个值,那么等式就成立了,是不是又超出了预期呢?
所以,当确定后面的数据是整数时,尤其是还有可能为0(这个可能代替所有的字符串了),你就千万不能再使用这个函数了,可使用key_exists来代替,但是后面的数据则需要使用array_flip进行倒转操作了。
我们再来看个示例
function search($keyWord, $stack) {//此处判断是应该更新还是插入 foreach ($stack as $key => $val) { if (in_array($keyWord, $val)) { return TRUE; } } return FALSE; }
当一个字符串被当作数组来去取值时,又会发生什么呢?php是一门容错性很强的语言,它会尽量帮你改正错误,所以很聪明地将你的引用下标转化为整数,当然就得到0了,那么字符串下标为0取值则又会得到第一个字符串的值,是不是又超出了你的预期呢?解决方法是,在引用下标之前,还是确认一下这个变量是不是一个数组吧,is_array。
虽然有许许多多的前辈遇到这样或那样的问题,也在不停地说,但是我们终究还是免不了,不停去犯错。这也许就是社会吧!大家都这么忙,哪有时间去破解你那烂代码! 哈哈

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
