PHP如何获取删除数组中指定位置的数字指定值得位置

& 把数组中的一部分去掉并用其它值取代
PHP array_splice 把数组中的一部分去掉并用其它值取代
array_splice
array_splice &
把数组中的一部分去掉并用其它值取代
array array_splice
( array &$input
, int $offset
[, int $length
[, array $
replacement
如果 offset 为正,则从 input
数组中该值指定的偏移量开始移除。如果 offset
为负,则从 input 末尾倒数该值指定的偏移量开始移除。
如果省略 length,则移除数组中从 offset
到结尾的所有部分。如果指定了 length
并且为正值,则移除这么多单元。如果指定了 length
并且为负值,则移除从 offset 到数组末尾倒数
length 为止中间所有的单元。小窍门:当给出了
replacement 时要移除从 offset
到数组末尾所有单元时,用 count($input) 作为 length。
如果给出了 replacement 数组,则被移除的单元被此数组中的单元替代。如果
offset 和 length
的组合结果是不会移除任何值,则 replacement
数组中的单元将被插入到 offset
指定的位置。注意替换数组中的键名不保留。如果用来替换的值只是一个单元,那么不需要给它加上
array(),除非该单元本身就是一个数组。
以下表达式以同样方式修改了 $input:
array_splice() 等价表达式
array_push($input, $x, $y)
array_splice($input, count($input), 0, array($x, $y))
array_pop($input)
array_splice($input, -1)
array_shift($input)
array_splice($input, 0, 1)
array_unshift($input, $x, $y)
array_splice($input, 0, 0, array($x, $y))
$input[$x] = $y // 对于键名和偏移量等值的数组
array_splice($input, $x, 1, $y)
返回一个包含被移除单元的数组。
Example #1 array_splice() 例子
&?php$input&=&array("red",&"green",&"blue",&"yellow");array_splice($input,&2);//&$input&is&now&array("red",&"green")$input&=&array("red",&"green",&"blue",&"yellow");array_splice($input,&1,&-1);//&$input&is&now&array("red",&"yellow")$input&=&array("red",&"green",&"blue",&"yellow");array_splice($input,&1,&count($input),&"orange");//&$input&is&now&array("red",&"orange")$input&=&array("red",&"green",&"blue",&"yellow");array_splice($input,&-1,&1,&array("black",&"maroon"));//&$input&is&now&array("red",&"green",//&&&&&&&&&&"blue",&"black",&"maroon")$input&=&array("red",&"green",&"blue",&"yellow");array_splice($input,&3,&0,&"purple");//&$input&is&now&array("red",&"green",//&&&&&&&&&&"blue",&"purple",&"yellow");?&
PHP数组 - 函数很偶然的机会被问到一个问题,如下:
$a = "123";
$a[$a[1]] = "5";
// 输出125
?& 原来字符串中的值可以被这样调用。
然后又对含有中文的字符串进行测试,如下:
$a = "我是123";
$a[$a[1]] = "5";
//会出现乱码
应该是因为汉子占两个字符,当被替换掉一个字符的时候,之后的显示就会出现乱码。
菜鸟一枚,如果有哪里说得不对,请各位大侠多多指正。
PHP中用下标符号[]去读取字符串的逻辑
PHP数组的操作(新建,取下标,内容)
php中用数组下标的方法来获取字符串的值
PHP判断数组下标有没有存在的方法
php中数组遍历的四种方式
php7.1 下标访问字符串变量可能造成混淆
PHP中读取(截取substr)字符串前N个字符或者从第几个字符开始取几个字符
PHP 检查给定的键名或索引是否存在于数组中 array_key_exists 函数
php数组打印下标及对应的值
PHP中使用for循环来遍历下标连续的二维索引数组
没有更多推荐了,Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
Array 数组
PHP 中的数组实际上是一个有序映射。映射是一种把 values
关联到 keys 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组,或列表(向量),散列表(是映射的一种实现),字典,集合,栈,队列以及更多可能性。由于数组元素的值也可以是另一个数组,树形结构和多维数组也是允许的。
解释这些结构超出了本手册的范围,但对于每种结构至少会提供一个例子。要得到这些结构的更多信息,建议参考有关此广阔主题的其它著作。
语言结构来新建一个数组。它接受任意数量用逗号分隔的
键(key) =& 值(value)对。
// 键(key)可是是一个整数
// 值(value)可以是任意类型的值
最后一个数组单元之后的逗号可以省略。通常用于单行数组定义中,例如常用
array(1, 2) 而不是
array(1, 2, )。对多行数组定义通常保留最后一个逗号,这样要添加一个新单元时更方便。
自 5.4 起可以使用短数组定义语法,用 [] 替代
Example #1 一个简单数组
&?php$array&=&array(&&&&"foo"&=&&"bar",&&&&"bar"&=&&"foo",);//&自&PHP&5.4&起$array&=&[&&&&"foo"&=&&"bar",&&&&"bar"&=&&"foo",];?&
key 可以是
。value 可以是任意类型。
此外 key 会有如下的强制转换:
包含有合法整型值的字符串会被转换为整型。例如键名
&8& 实际会被储存为
8。但是 &08&
则不会强制转换,因为其不是一个合法的十进制数值。
浮点数也会被转换为整型,意味着其小数部分会被舍去。例如键名
8.7 实际会被储存为 8。
布尔值也会被转换成整型。即键名
true 实际会被储存为 1
而键名 false 会被储存为 0。
会被转换为空字符串,即键名
null 实际会被储存为 &&。
数组和对象不能被用为键名。坚持这么做会导致警告:Illegal offset type。
如果在数组定义中多个单元都使用了同一个键名,则只使用了最后一个,之前的都被覆盖了。
Example #2 类型强制与覆盖示例
&?php$array&=&array(&&&&1&&&&=&&"a",&&&&"1"&&=&&"b",&&&&1.5&&=&&"c",&&&&true&=&&"d",);var_dump($array);?&
以上例程会输出:
array(1) {
string(1) &d&
上例中所有的键名都被强制转换为 1,则每一个新单元都会覆盖前一个的值,最后剩下的只有一个
PHP 数组可以同时含有
类型的键名,因为
PHP 实际并不区分索引数组和关联数组。
如果对给出的值没有指定键名,则取当前最大的整数索引值,而新的键名将是该值加一。如果指定的键名已经有了值,则该值会被覆盖。
Example #3 混合
&?php$array&=&array(&&&&"foo"&=&&"bar",&&&&"bar"&=&&"foo",&&&&100&&&=&&-100,&&&&-100&&=&&100,);var_dump($array);?&
以上例程会输出:
array(4) {
string(3) &bar&
string(3) &foo&
key 为可选项。如果未指定,PHP
将自动使用之前用过的最大
键名加上 1 作为新的键名。
Example #4 没有键名的索引数组
&?php$array&=&array("foo",&"bar",&"hallo",&"world");var_dump($array);?&
以上例程会输出:
array(4) {
string(3) &foo&
string(3) &bar&
string(5) &hallo&
string(5) &world&
还可以只对某些单元指定键名而对其它的空置:
Example #5 仅对部分单元指定键名
&?php$array&=&array(&&&&&&&&&"a",&&&&&&&&&"b",&&&&6&=&&"c",&&&&&&&&&"d",);var_dump($array);?&
以上例程会输出:
array(4) {
string(1) &a&
string(1) &b&
string(1) &c&
string(1) &d&
可以看到最后一个值 &d& 被自动赋予了键名
7。这是由于之前最大的整数键名是 6。
用方括号语法访问数组单元
数组单元可以通过 array[key] 语法来访问。
Example #6 访问数组单元
&?php$array&=&array(&&&&"foo"&=&&"bar",&&&&42&&&&=&&24,&&&&"multi"&=&&array(&&&&&&&&&"dimensional"&=&&array(&&&&&&&&&&&&&"array"&=&&"foo"&&&&&&&&&)&&&&));var_dump($array["foo"]);var_dump($array[42]);var_dump($array["multi"]["dimensional"]["array"]);?&
以上例程会输出:
string(3) &bar&
string(3) &foo&
方括号和花括号可以互换使用来访问数组单元(例如 $array[42]
和 $array{42} 在上例中效果相同)。
自 PHP 5.4 起可以用直接对函数或方法调用的结果进行数组解引用,在此之前只能通过一个临时变量。
自 PHP 5.5 起可以直接对一个数组原型进行数组解引用。
Example #7 数组解引用
&?phpfunction&getArray()&{&&&&return&array(1,&2,&3);}//&on&PHP&5.4$secondElement&=&getArray()[1];//&previously$tmp&=&getArray();$secondElement&=&$tmp[1];//&orlist(,&$secondElement)&=&getArray();?&
试图访问一个未定义的数组键名与访问任何未定义变量一样:会导致
E_NOTICE 级别错误信息,其结果为 NULL。
用方括号的语法新建/修改
可以通过明示地设定其中的值来修改一个已有数组。
这是通过在方括号内指定键名来给数组赋值实现的。也可以省略键名,在这种情况下给变量名加上一对空的方括号([])。
$arr[key] = value;
$arr[] = value;
// key 可以是
// value 可以是任意类型的值
还不存在,将会新建一个,这也是另一种新建数组的方法。不过并不鼓励这样做,因为如果
$arr 已经包含有值(例如来自请求变量的 )则此值会保留而
[] 实际上代表着。初始化变量的最好方式是直接给其赋值。。
要修改某个值,通过其键名给该单元赋一个新值。要删除某键值对,对其调用
如上所述,如果给出方括号但没有指定键名,则取当前最大整数索引值,新的键名将是该值加上
1(但是最小为 0)。如果当前还没有整数索引,则键名将为
注意这里所使用的最大整数键名不一定当前就在数组中。它只要在上次数组重新生成索引后曾经存在过就行了。以下面的例子来说明:
以上例程会输出:
有很多操作数组的函数,参见一节。
函数允许删除数组中的某个键。但要注意数组将不会重建索引。如果需要删除后重建索引,可以用
控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。
数组做什么和不做什么
为什么 $foo[bar] 错了?
应该始终在用字符串表示的数组索引上加上引号。例如用
$foo['bar'] 而不是 $foo[bar]。但是为什么呢?可能在老的脚本中见过如下语法:
这样是错的,但可以正常运行。那么为什么错了呢?原因是此代码中有一个未定义的常量(bar)而不是字符串('bar'-注意引号),而
PHP 可能会在以后定义此常量,不幸的是你的代码中有同样的名字。它能运行,是因为
PHP 自动将裸字符串(没有引号的字符串且不对应于任何已知符号)转换成一个其值为该裸字符串的正常字符串。例如,如果没有常量定义为
bar,PHP 将把它替代为 'bar' 并使用之。
这并不意味着总是给键名加上引号。用不着给键名为或的加上引号,否则会使 PHP
不能解析它们。
以上例程会输出:
Checking 0:
Notice: Undefined index:
$i in /path/to/script.html on line 9
Notice: Undefined index:
$i in /path/to/script.html on line 11
Checking 1:
Notice: Undefined index:
$i in /path/to/script.html on line 9
Notice: Undefined index:
$i in /path/to/script.html on line 11
演示此行为的更多例子:
E_NOTICE 级别的错误(将其设为
E_ALL)时将看到这些错误。默认情况下
被关闭不显示这些。
和在一节中规定的一样,在方括号(“[”和“]”)之间必须有一个表达式。这意味着可以这样写:
这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量,可能之前已经见过:
注意 E_ERROR 也是个合法的标识符,就和第一个例子中的
bar 一样。但是上一个例子实际上和如下写法是一样的:
因为 E_ERROR 等于 1,等等。
那么为什么这样做不好?
也许有一天,PHP 开发小组可能会想新增一个常量或者关键字,或者用户可能希望以后在自己的程序中引入新的常量,那就有麻烦了。例如已经不能这样用
empty 和 default 这两个词了,因为他们是。
重申一次,在双引号字符串中,不给索引加上引号是合法的因此
&$foo[bar]&
是合法的(“合法”的原文为 valid。在实际测试中,这么做确实可以访问数组的该元素,但是会报一个常量未定义的
notice。无论如何,强烈建议不要使用 $foo[bar]这样的写法,而要使用 $foo['bar']
来访问数组中元素。--haohappy 注)。至于为什么参见以上的例子和中的解释。
转换为数组
对于任意 ,,,
类型,如果将一个值转换为数组,将得到一个仅有一个元素的数组,其下标为
0,该元素即为此标量的值。换句话说,(array)$scalarValue 与
array($scalarValue) 完全一样。
类型转换为
,则结果为一个数组,其单元为该对象的属性。键名将为成员变量名,不过有几点例外:整数属性不可访问;私有变量前会加上类名作前缀;保护变量前会加上一个
'*' 做前缀。这些前缀的前后都各有一个 NULL 字符。这会导致一些不可预知的行为:
上例会有两个键名为 'AA',不过其中一个实际上是 '\0A\0A'。
将 NULL 转换为
会得到一个空的数组。
和来比较数组。
PHP 中的数组类型有非常多的用途。以下是一些示例:
Example #8 使用 array()
&?php//&Array&as&(property-)map$map&=&array(&'version'&&&&=&&4,&&&&&&&&&&&&&&'OS'&&&&&&&&&=&&'Linux',&&&&&&&&&&&&&&'lang'&&&&&&&=&&'english',&&&&&&&&&&&&&&'short_tags'&=&&true&&&&&&&&&&&&);&&&&&&&&&&&&//&strictly&numerical&keys$array&=&array(&7,&&&&&&&&&&&&&&&&8,&&&&&&&&&&&&&&&&0,&&&&&&&&&&&&&&&&156,&&&&&&&&&&&&&&&&-10&&&&&&&&&&&&&&);//&this&is&the&same&as&array(0&=&&7,&1&=&&8,&...)$switching&=&array(&&&&&&&&&10,&//&key&=&0&&&&&&&&&&&&&&&&&&&&5&&&&=&&&6,&&&&&&&&&&&&&&&&&&&&3&&&&=&&&7,&&&&&&&&&&&&&&&&&&&&&'a'&&=&&&4,&&&&&&&&&&&&&&&&&&&&&&&&&&&&11,&//&key&=&6&(maximum&of&integer-indices&was&5)&&&&&&&&&&&&&&&&&&&&'8'&&=&&&2,&//&key&=&8&(integer!)&&&&&&&&&&&&&&&&&&&&'02'&=&&77,&//&key&=&'02'&&&&&&&&&&&&&&&&&&&&0&&&&=&&12&&//&the&value&10&will&be&overwritten&by&12&&&&&&&&&&&&&&&&&&);&&&&&&&&&&&&&&&&&&//&empty&array$empty&=&array();&&&&&&&&&?&
Example #9 集合
&?php$colors&=&array('red',&'blue',&'green',&'yellow');foreach&($colors&as&$color)&{&&&&echo&"Do&you&like&$color?\n";}?&
以上例程会输出:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
直接改变数组的值自 PHP 5 起可以通过引用传递来做到。之前的版本需要需要采取变通的方法:
Example #10 在循环中改变单元
&?php//&PHP&5foreach&($colors&as&&$color)&{&&&&$color&=&strtoupper($color);}unset($color);&/*&ensure&that&following&writes&to$color&will&not&modify&the&last&array&element&*///&Workaround&for&older&versionsforeach&($colors&as&$key&=&&$color)&{&&&&$colors[$key]&=&strtoupper($color);}print_r($colors);?&
以上例程会输出:
[0] =& RED
[1] =& BLUE
[2] =& GREEN
[3] =& YELLOW
本例生成一个下标从 1 开始的数组。
Example #11 下标从 1 开始的数组
&?php$firstquarter&&=&array(1&=&&'January',&'February',&'March');print_r($firstquarter);?&
以上例程会输出:
[1] =& 'January'
[2] =& 'February'
[3] =& 'March'
Example #12 填充数组
&?php//&fill&an&array&with&all&items&from&a&directory$handle&=&opendir('.');while&(false&!==&($file&=&readdir($handle)))&{&&&&$files[]&=&$file;}closedir($handle);&?&
数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见。可以用
函数来数出数组中元素的个数。
Example #13 数组排序
&?phpsort($files);print_r($files);?&
因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。
Example #14 递归和多维数组
&?php$fruits&=&array&(&"fruits"&&=&&array&(&"a"&=&&"orange",&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"b"&=&&"banana",&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"c"&=&&"apple"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&),&&&&&&&&&&&&&&&&&&"numbers"&=&&array&(&1,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&2,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&3,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&4,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&5,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&6&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&),&&&&&&&&&&&&&&&&&&"holes"&&&=&&array&(&&&&&&"first",&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&5&=&&"second",&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"third"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&)&&&&&&&&&&&&&&&&);//&Some&examples&to&address&values&in&the&array&above&echo&$fruits["holes"][5];&&&&//&prints&"second"echo&$fruits["fruits"]["a"];&//&prints&"orange"unset($fruits["holes"][0]);&&//&remove&"first"//&Create&a&new&multi-dimensional&array$juices["apple"]["green"]&=&"good";&?&
数组(Array) 的赋值总是会涉及到值的拷贝。使用通过引用来拷贝数组。
In array(key=&value) construct key is also an expression.This works fine:& $a = array(& & 1& && =&0,& & 1+1&& =&1,& & $k& & =&2,& & $x.'4'=&3& );
please note that when arrays are copied, the "reference status" of their members is preserved ().
I think your first, main example is needlessly confusing, very confusing to newbies:$array = array(& & "foo" =& "bar",& & "bar" =& "foo",);It should be removed. For newbies:An array index can be any string value, even a value that is also a value in the array. The value of array["foo"] is "bar".The value of array["bar"] is "foo"The following expressions are both true:$array["foo"] == "bar"$array["bar"] == "foo"
Note that array value buckets are reference-safe, even through serialization.
&?php
$x='initial';
$test=array('A'=&&$x,'B'=&&$x);
$test=unserialize(serialize($test));
$test['A']='changed';
echo $test['B']; ?&
This can be useful in some cases, for example saving RAM within complex structures.
"If you convert a NULL value to an array, you get an empty array."
This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.
&?php $values = search(...); ?&
Now you want to merge the array with another array. What do we do if $values is NULL? No problem:
&?php $combined = array_merge((array)$values, $other); ?&
--- quote ---Note:Both square brackets and curly braces can be used interchangeably for accessing array elements--- quote end ---At least for php 5.4 and 5.6; if function returns an array, the curly brackets does not work directly accessing function result, eg. WillReturnArray(){1} . This will give "syntax error, unexpected '{' in...".Personally I use only square brackets, expect for accessing single char in string. Old habits...
Just a comment to this:"&?php$a['a'] = null;$a['b'] = array();echo $a['a']['non-existent']; echo $a['b']['non-existent']; ?&I added this bug to bugs.php.net ()however I made tests with php4, 5.4 and 5.5 versions and all behave the same way.This, in my point of view, should be cast to an array type and throw the same error.This is, according to the documentation on this page, wrong.From doc:"Note:Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.""$a['a'] is not an array. It is null. That rule does not applyInstead $a['b'] is an array. Rule is applied.
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:&html&&body&&?php& & printf("POST: "); print_r($_POST); printf("&br/&");?&&form method="post" action="&?php echo $_SERVER['PHP_SELF']; ?&"&& & &input type="hidden" name="Windows3.1" value="Sux"&& & &input type="submit" value="Click" /&&/form&&/body&&/html&Once you click on the button, the page displays the following:POST: Array ( [Windows3_1] =& Sux )
Used to creating arrays like this in Perl?@array = ("All", "A".."Z");Looks like we need the range() function in PHP:&?php$array = array_merge(array('All'), range('A', 'Z'));?&You don't need to array_merge if it's just one range:&?php$array = range('A', 'Z');?&
// On PHP 7.1 until Jan. 20 2017$testVar = "";$testVar[2] = "Meine eigene L?sung";echo $testVar[2];// Result:// Meine eigene L?sung =& $testVar is an ARRAY// On PHP 7.1.1 after Jan. 20 2017$testVar = "";$testVar[2] = "Meine eigene L?sung";echo $testVar[2];// Result:// M =& $testVar is a STRING !!!
Note that objects of classes extending ArrayObject SPL class are treated as arrays, and not as objects when converting to array.&?phpclass ArrayObjectExtended extends ArrayObject{& & private $private = 'private';& & public $hello = 'world';}$object = new ArrayObjectExtended();$array = (array) $object;var_export($array);?&
&?php$a['a'] = null;$a['b'] = array();echo $a['a']['non-existent']; echo $a['b']['non-existent']; ?&I added this bug to bugs.php.net ()however I made tests with php4, 5.4 and 5.5 versions and all behave the same way.This, in my point of view, should be cast to an array type and throw the same error.This is, according to the documentation on this page, wrong.From doc:"Note:Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL."
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:&?phpforeach ( $arr as $key =& &$value ){& & $value = 1;}$value = 159;?&Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1').Bad results can also appear in nested foreach loops (the same reason as above).So either unset $value after each foreach or better use the longer form:&?phpforeach ( $arr as $key =& $value ){& & $arr[ $key ] = 1;}?&
There is another kind of array (php&=& 5.3.0) produced by $array = new SplFixedArray(5);Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation. Supposing a large string-keyed array $arr=['string1'=&$data1, 'string2'=&$data2 etc....]when getting the keyed data with $data=$arr['string1'];php does *not* have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away.However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See
for more details.]
Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now...
I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean:
$a1 = array( "a" =& 0, "b" =& 1 );
$a2 = array( "aa" =& 00, "bb" =& 11 );
$together = array( $a1, $a2 );
foreach( $together as $single ) {
& & $single[ "c" ] = 3 ;
}
print_r( $together );
foreach( $together as $key =& $value ) {
& & $together[$key]["c"] = 3 ;
}
print_r( $together );
It is true that "array assignment always involves value copying", but the copy is a "lazy copy". This means that the data of the two variables occupy the same memory as long as no array element changes.E.g., if you have to pass an array to a function that only needs to read it, there is no advantage at all in passing it by reference.
FIX FOR PHP 7.2 UNDEFINED CONSTANT WARNING MESSAGE "Use of undefined constant ..."Recursively clean up all files in a PHP project and automatically quote all strings which are undefined constants used inside square brackets for the array syntax.Observation: this fix only targets array usage like $foo[bar] which will be automatically transformed into $foo['bar']. The clean up process DOES NOT parse and compute a list of defined constants in your project, in order to white-list them for usage without quotes in all possible contexts.It's recommended to run it for your project on DEV first, check functionality and then push to LIVE.QUICK USAGE:git clone
lx-utilscd lx-utils && composer install --no-devphp run/cleanUpSquareBrackets.php /path/you/want/to/clean/upThe complete usage instructions and source code are on the page:
Since PHP 7.1, the string will not be converted to array automatically.Below codes will fail:$a=array();$a['a']='';$a['a']['b']='';& //Warning: Illegal string offset 'b'//Warning: Cannot assign an empty string to a string offsetYou have to change to as below:$a=array();$a['a']=array(); // Declare it is an array first$a['a']['b']='';
Please note that adding the magic __toString() method to your objects will not allow you to seek an array with it, it still throws an Illegal Offset warning.The solution is to cast it to a string first, like this$array[(string) $stringableObject]
Why not to user one-based arrays:&?php$a& = array(1 =& 'a', 'b', 'd');print_r($a);array_splice($a,2,0,'c');print_r($a);?&output:Array ( [1] =& a [2] =& b [3] =& d ) Array ( [0] =& a [1] =& b [2] =& c [3] =& d )
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer. Example:$arr = ['bebe' =& 'Bob', 'age' =& 23, 'too' =& 23 ];xdebug_debug_zval( 'arr' );Output:arr:(refcount=2, is_ref=0)array (size=3)& 'bebe' =& (refcount=1, is_ref=0)string 'Bob' (length=3)& 'age' =& (refcount=0, is_ref=0)int 23& 'too' =& (refcount=0, is_ref=0)int 23but :$arr = ['bebe' =& 'Bob', 'age' =& 23, 'too' =& '23' ];xdebug_debug_zval( 'arr' );will produce:arr:(refcount=2, is_ref=0)array (size=3)& 'bebe' =& (refcount=1, is_ref=0)string 'Bob' (length=3)& 'age' =& (refcount=0, is_ref=0)int 23& 'too' =& (refcount=1, is_ref=0)string '23' (length=2)or :$arr = ['bebe' =& 'Bob', 'age' =& [1,2], 'too' =& [1,2] ];xdebug_debug_zval( 'arr' );Output:arr:(refcount=2, is_ref=0)array (size=3)& 'bebe' =& (refcount=1, is_ref=0)string 'Bob' (length=3)& 'age' =& (refcount=2, is_ref=0)& & array (size=2)& & & 0 =& (refcount=0, is_ref=0)int 1& & & 1 =& (refcount=0, is_ref=0)int 2& 'too' =& (refcount=2, is_ref=0)& & array (size=2)& & & 0 =& (refcount=0, is_ref=0)int 1& & & 1 =& (refcount=0, is_ref=0)int 2
Sometimes I need to match fieldnames from database tables. But if a source field is used many times you can not use a hash "=&", because it overrides the key.My approach is to use a comma separated array and use a while-loop in conjunction with each. Having that you can iterate key/value based, but may have a key multiple times.$fieldmap = array(& & 'id', 'import_id',& & 'productname', 'title',& & 'datetime_online', 'onlineDate',& & 'datetime_test_final', 'offlineDate',& & 'active', 'status',& & 'questionaire_intro', 'text_lead',& & 'datetime_online', 'createdAt',& & 'datetime_online', 'updatedAt');while(list(,$key) = each($fieldmap)){& & list(,$value) = each($fieldmap);& & echo "$key: $value\n";}
This page should include details about how associative arrays are implemened inside PHP; e.g. using hash-maps or b-trees.This has important implictions on the permance characteristics of associative arrays and how e.g. b-tree are slow to insert but handle collisions better than hashmaps.& Hashmaps are faster if there are no collisions, but are slower to retrieve when there are collisions.& These factors have implictions on how associative arrays should be used.
On array recursion...
Given the following code:
&?php
$myarray = array('test',123);
$myarray[] = &$myarray;
print_r($myarray);
?&
The print_r() will display *RECURSION* when it gets to the third element of the array.
There doesn't appear to be any other way to scan an array for recursive references, so if you need to check for them, you'll have to use print_r() with its second parameter to capture the output and look for the word *RECURSION*.
It's not an elegant solution, but it's the only one I've found, so I hope it helps someone.
/* * Name : Aditya Mehrotra
*/&?php$exampleArray = array(0,& & 1,& & "2." =& 56,& & 2 =& 2,& & 3.9999 =& 3,& & 3 =& 3.1,& & true =& 4,& & false =& 6,);print_r($exampleArray);print_r(array_keys($exampleArray));
Its worth noting that there does not appear to be any functional limitations on the length or content of string indexes. The string indexes for your arrays can contain any characters, including new line characters, and can be of any length:&?php$key = "XXXXX";$test = array($key =& "test5");for ($x = 0; $x & 500; $x++) {& $key .= "X";& $value = "test" . strlen($key);& $test[$key] = $value;}echo "&pre&";print_r($test);echo "&/pre&";?&Keep in mind that using extremely long array indexes is not a good practice and could cost you lots of extra CPU time. However, if you have to use a long string as an array index you won't have to worry about the length or content.
авкаdkskswdlslsdkskdsdksofkfeoewpwwowffkvvvkvofvkvkfv

我要回帖

更多关于 如何为数组元素赋值 的文章

 

随机推荐