(PHP 5 >= 5.3.0, PHP 7, PHP
array_replace — Заменяет элементы массива элементами других переданных массивов
Описание
array_replace(array $array
, array ...$replacements
): array
array_replace() не рекурсивная: значения первого массива
будут заменены вне зависимости от типа значений второго массива, даже если
это будут вложенные массивы.
Список параметров
-
array
-
Массив, элементы которого требуется заменить.
-
replacements
-
Массивы, из которых будут браться элементы для замены.
Значения следующего массива затирают значения предыдущего.
Возвращаемые значения
Возвращает массив (array).
Примеры
Пример #1 Пример использования array_replace()
<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>
Результат выполнения данного примера:
Array ( [0] => grape [1] => banana [2] => apple [3] => raspberry [4] => cherry )
Смотрите также
- array_replace_recursive() — Рекурсивно заменяет элементы первого массива элементами переданных массивов
- array_merge() — Сливает один или большее количество массивов
steelpandrummer ¶
10 years ago
<?php
// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values$values = array
(
'Article'=>'24497',
'Type'=>'LED',
'Socket'=>'E27',
'Dimmable'=>'',
'Wattage'=>'10W'
);$keys = array_fill_keys(array('Article','Wattage','Dimmable','Type','Foobar'), ''); // wanted array with empty value$allkeys = array_replace($keys, array_intersect_key($values, $keys)); // replace only the wanted keys$notempty = array_filter($allkeys, 'strlen'); // strlen used as the callback-function with 0==falseprint '<pre>';
print_r($allkeys);
print_r($notempty);/*
Array
(
[Article] => 24497
[Wattage] => 10W
[Dimmable] =>
[Type] => LED
[Foobar] =>
)
Array
(
[Article] => 24497
[Wattage] => 10W
[Type] => LED
)
*/
?>
marvin_elia at web dot de ¶
8 years ago
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.
/**
* @param array $array
* @param array $replacements
* @param boolean $override
* @return array
*/
function array_replace_keys(array $array, array $replacements, $override = false) {
foreach ($replacements as $old => $new) {
if(is_int($new) || is_string($new)){
if(array_key_exists($old, $array)){
if(array_key_exists($new, $array) && $override === false){
continue;
}
$array[$new] = $array[$old];
unset($array[$old]);
}
}
}
return $array;
}
ali dot sweden19 at yahoo dot com ¶
7 years ago
Here is a simple array_replace_keys function:
/**
* This function replaces the keys of an associate array by those supplied in the keys array
*
* @param $array target associative array in which the keys are intended to be replaced
* @param $keys associate array where search key => replace by key, for replacing respective keys
* @return array with replaced keys
*/
private function array_replace_keys($array, $keys)
{
foreach ($keys as $search => $replace) {
if ( isset($array[$search])) {
$array[$replace] = $array[$search];
unset($array[$search]);
}
}
return $array;
}
// Test Drive
print_r(array_replace_keys(['one'=>'apple', 'two'=>'orange'], ['one'=>'ett', 'two'=>'tvo']);
// Output
array(
'ett'=>'apple',
'tvo'=>'orange'
)
mail at romansklenar dot cz ¶
13 years ago
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:
<?php
...
$count = func_num_args();
for (
$i = 1; $i < $count; $i++) {
...
}
...
?>
Check on this code:
<?php
$base = array('id' => NULL, 'login' => NULL, 'credit' => NULL);
$arr1 = array('id' => 2, 'login' => NULL, 'credit' => 5);
$arr2 = array('id' => NULL, 'login' => 'john.doe', 'credit' => 100);
$result = array_replace($base, $arr1, $arr2);
/*
correct output:
array(3) {
"id" => NULL
"login" => string(8) "john.doe"
"credit" => int(100)
}
your output:
array(3) {
"id" => int(2)
"login" => NULL
"credit" => int(5)
}
*/
?>
Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...
gmastro77 at gmail dot com ¶
9 years ago
In some cases you might have a structured array from the database and one
of its nodes goes like this;
<?php
# a random node structure
$arr = array(
'name' => 'some name',
'key2' => 'value2',
'title' => 'some title',
'key4' => 4,
'json' => '[1,0,1,1,0]'
);# capture these keys values into given order
$keys = array( 'name', 'json', 'title' );
?>
Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following
<?php
# string to transform
$string = "<p>name: %s, json: %s, title: %s</p>";# flip keys once, we will use this twice
$keys = array_flip( $keys );# get values from $arr
$test = array_intersect_key( $arr, $keys );# still not good enough
echo vsprintf( $string, $test );
// output --> name: some name, json: some title, title: [1,0,1,1,0]
# usage of array_replace to get exact order and save the day
$test = array_replace( $keys, $test );# exact output
echo vsprintf( $string, $test );
// output --> name: some name, json: [1,0,1,1,0], title: some title?>
I hope that this will save someone's time.
polecat at p0lecat dot com ¶
12 years ago
I got hit with a noob mistake. :)
When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.
With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. :)
<?php
// Polecat's Multi-dimensional array_replace function
// Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact
function polecat_array_replace( array &$array1, array &$array2 ) {
// This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions
if(!function_exists('tier_parse')){
function tier_parse(array &$t_array1, array&$t_array2) {
foreach ($t_array2 as $k2 => $v2) {
if (is_array($t_array2[$k2])) {
tier_parse($t_array1[$k2], $t_array2[$k2]);
} else {
$t_array1[$k2] = $t_array2[$k2];
}
}
return $t_array1;
}
}
foreach (
$array2 as $key => $val) {
if (is_array($array2[$key])) {
tier_parse($array1[$key], $array2[$key]);
} else {
$array1[$key] = $array2[$key];
}
}
return $array1;
}
?>
[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:
<?php
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );
$array2 = array( "food" => "wine");
$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
?>
This is will replace the value for "food" for "dewberry" with "wine".
The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.
I hope this helps atleast one person for all that I've gained from this site.
kyberprizrak ¶
8 years ago
if(!function_exists('array_replace'))
{
function array_replace()
{
$args = func_get_args();
$num_args = func_num_args();
$res = array();
for($i=0; $i<$num_args; $i++)
{
if(is_array($args[$i]))
{
foreach($args[$i] as $key => $val)
{
$res[$key] = $val;
}
}
else
{
trigger_error(__FUNCTION__ .'(): Argument #'.($i+1).' is not an array', E_USER_WARNING);
return NULL;
}
}
return $res;
}
}
sun at drupal dot org ¶
11 years ago
Instead of calling this function, it's often faster and simpler to do this instead:
<?php
$array_replaced = $array2 + $array1;
?>
If you need references to stay intact:
<?php
$array2 += $array1;
?>
lm713 ¶
8 years ago
If the arrays are associative (that is, their keys are strings), then I believe this function is identical to (the older) array_merge.
ricardophp yahoocombr ¶
10 months ago
Concerning the affirmation:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator
Clearing the fact (it means ...):
If the first array have a key and a value it will not be overlap by the new array. therefore if you have an array like [1=>"alpha", 2=>"beta"] and you got a new array telling [1=>"Alpha", 3=>"Gamma"] the final array will be [1=>"alpha", 2=>"beta", 3=>"Gamma"]. The values of first array will not be modified in the result array.
So, if you are building a concatenation array where the values sometimes overlaps each other keys and you must preserve values you better use array_merge instead "plus" sign
projacore at gmail dot com ¶
7 years ago
You can also use:
<?php
$myarray = [
"Orange",
"572" => "Banana",
"omg" => "Chili",
"nevermind" => "mango"
];$myarray[0] = "NO-Orange";
$myarray["572"] = "BANANAPHONE!!!";
$myarray["omg"] = "NO-Chili";print_r($myarray);?>
RESULT:
Array
(
[0] => NO-Orange
[572] => BANANAPHONE!!!
[omg] => NO-Chili
[nevermind] => mango
)
with regards
polecat at p0lecat dot com ¶
12 years ago
I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );
$array2 = array( "food" => "wine");
$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
This is will replace the value for "food" for "dewberry" with "wine".
The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.
I hope this helps atleast one person for all that I've gained from this site.
Anonymous ¶
7 years ago
The documentation is wrongly phrased: "array_replace() replaces the values of array1" No replacing is done. A new array is created which looks like the one that would have resulted from the described replacement.
If you want to augment the set of indices in an array, use
array_to_be_modified += array_with_indices_to_add;
tufan dot oezduman at googlemail dot com ¶
13 years ago
a little enhancement to dyer85 at gmail dot com's function below:
<?php
if (!function_exists('array_replace'))
{
function array_replace( array &$array, array &$array1, $filterEmpty=false )
{
$args = func_get_args();
$count = func_num_args()-1;
for (
$i = 0; $i < $count; ++$i) {
if (is_array($args[$i])) {
foreach ($args[$i] as $key => $val) {
if ($filterEmpty && empty($val)) continue;
$array[$key] = $val;
}
}
else {
trigger_error(
__FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
E_USER_WARNING
);
return NULL;
}
}
return
$array;
}
}
?>
this will allow you to "tetris-like" merge arrays:
<?php
$a
= array(
0 => "foo",
1 => "",
2 => "baz"
);
$b= array(
0 => "",
1 => "bar",
2 => ""
);print_r(array_replace($a,$b, true));?>
results in:
Array
(
[0] => foo
[1] => bar
[2] => baz
)
ivijan dot stefan at gmail dot com ¶
6 years ago
If you work on some realy old server below PHP5 you can use array_merge like "necessary evil" to replace values in array:
Here is example how you can use this:
<?php
if(function_exists("array_replace") && version_compare(phpversion(), '5.3.0', '>='))
$data = array_replace($array1, $array2); // (PHP 5 >= 5.3.0)
else
$data = array_merge($array1, $array2); // (PHP 5 < 5.3.0)
var_dump($data);
?>
This can also help someplugin developers to cover some old PHP versions.
I was looking for some standard PHP function to replace some value of an array with other, but surprisingly I haven’t found any, so I have to write my own:
function array_replace_value(&$ar, $value, $replacement)
{
if (($key = array_search($ar, $value)) !== FALSE) {
$ar[$key] = $replacement;
}
}
But I still wonder — for such an easy thing there must already be some function for it! Or maybe much easier solution than this one invented by me?
Note that this function will only do one replacement. I’m looking for existing solutions that similarly replace a single occurrence, as well as those that replace all occurrences.
outis
74.4k21 gold badges149 silver badges219 bronze badges
asked Dec 29, 2011 at 14:05
12
Instead of a function that only replaces occurrences of one value in an array, there’s the more general array_map
:
array_map(function ($v) use ($value, $replacement) {
return $v == $value ? $replacement : $v;
}, $arr);
To replace multiple occurrences of multiple values using array of value => replacement:
array_map(function ($v) use ($replacement) {
return isset($replacement[$v]) ? $replacement[$v] : $v;
}, $arr);
To replace a single occurrence of one value, you’d use array_search
as you do. Because the implementation is so short, there isn’t much reason for the PHP developers to create a standard function to perform the task. Not to say that it doesn’t make sense for you to create such a function, if you find yourself needing it often.
answered Dec 29, 2011 at 14:19
outisoutis
74.4k21 gold badges149 silver badges219 bronze badges
5
While there isn’t one function equivalent to the sample code, you can use array_keys
(with the optional search value parameter), array_fill
and array_replace
to achieve the same thing:
EDIT by Tomas: the code was not working, corrected it:
$ar = array_replace($ar,
array_fill_keys(
array_keys($ar, $value),
$replacement
)
);
Tomas
56.6k48 gold badges232 silver badges368 bronze badges
answered Dec 29, 2011 at 14:09
Deept RaghavDeept Raghav
1,43013 silver badges14 bronze badges
5
If performance is an issue, one may consider not to create multiple functions within array_map()
. Note that isset()
is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
rmorse
7266 silver badges17 bronze badges
answered Sep 1, 2015 at 0:12
BurninLeoBurninLeo
4,1304 gold badges37 silver badges54 bronze badges
Try this function.
public function recursive_array_replace ($find, $replace, $array) {
if (!is_array($array)) {
return str_replace($find, $replace, $array);
}
$newArray = [];
foreach ($array as $key => $value) {
$newArray[$key] = recursive_array_replace($find, $replace, $value);
}
return $newArray;
}
Cheers!
Joshua
4,7642 gold badges30 silver badges44 bronze badges
answered Dec 29, 2011 at 14:13
Prasad RajapakshaPrasad Rajapaksha
6,05210 gold badges36 silver badges52 bronze badges
1
$ar[array_search('green', $ar)] = 'value';
answered Mar 11, 2019 at 14:26
2
Depending whether it’s the value, the key or both you want to find and replace on you could do something like this:
$array = json_decode( str_replace( $replace, $with, json_encode( $array ) ), true );
I’m not saying this is the most efficient or elegant, but nice and simple.
answered Sep 5, 2016 at 19:50
1
What about array_walk()
with callback?
$array = ['*pasta', 'cola', 'pizza'];
$search = '*';
$replace = '*';
array_walk($array,
function (&$v) use ($search, $replace){
$v = str_replace($search, $replace, $v);
}
);
print_r($array);
answered Sep 13, 2016 at 14:27
user3396065user3396065
5405 silver badges15 bronze badges
1
Based on Deept Raghav
‘s answer, I created the follow solution that does regular expression search.
$arr = [
'Array Element 1',
'Array Element 2',
'Replace Me',
'Array Element 4',
];
$arr = array_replace(
$arr,
array_fill_keys(
array_keys(
preg_grep('/^Replace/', $arr)
),
'Array Element 3'
)
);
echo '<pre>', var_export($arr), '</pre>';
PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt
answered Mar 4, 2016 at 22:45
1
PHP 8, a strict version to replace one string value into another:
array_map(static fn (string $value): string => $value === $find ? $replace : $value, $array);
An example — replace value foo
by bar
:
array_map(static fn (string $value): string => $value === 'foo' ? 'bar' : $value, $array);
answered Aug 9, 2021 at 20:38
1
You can make full string matches without specifying the keys of qualifying values, by calling preg_replace()
with a pattern containing start and end of string anchors (^
, $
). If your search term may contain characters which have a special meaning to the regex engine, then be sure to escape them with preg_quote()
to avoid breakage. While regex is not entirely called for, regex offers some very convenient ways to tweak the search term handling. (Demo)
function array_replace_value(&$ar, $value, $replacement)
{
$ar = preg_replace(
'/^' . preg_quote($value, '/') . '$/',
$replacement,
$ar
);
}
I might be more inclined to use array_map()
with arrow function syntax so that global variables can be accessed within the custom function scope. (Demo)
$needle = 'foo';
$newValue = 'bar';
var_export(
array_map(fn($v) => $v === $needle ? $newValue : $v, $array)
);
answered Dec 13, 2022 at 12:05
mickmackusamickmackusa
41.8k12 gold badges82 silver badges125 bronze badges
$ar = array(1,2,3,4,5,6,7,8);
$find = array(2,3);
$replace = array(13);
function update_bundle_package($ar,$find,$replace){
foreach ($find as $x => $y) {
///TO REMOVE PACKAGE
if (($key = array_search($y, $ar)) !== false) {
unset($ar[$key]);
}
///TO REMOVE PACKAGE
}
$ar = array_merge($ar, $replace);
}
answered Dec 22, 2022 at 8:34
1
<b>$green_key = array_search('green', $input); // returns the first key whose value is 'green'
$input[$green_key] = ‘apple’; // replace ‘green’ with ‘apple’
answered Dec 29, 2011 at 14:17
Muthu KrishnanMuthu Krishnan
1,6642 gold badges10 silver badges15 bronze badges
2
I was looking for some standard PHP function to replace some value of an array with other, but surprisingly I haven’t found any, so I have to write my own:
function array_replace_value(&$ar, $value, $replacement)
{
if (($key = array_search($ar, $value)) !== FALSE) {
$ar[$key] = $replacement;
}
}
But I still wonder — for such an easy thing there must already be some function for it! Or maybe much easier solution than this one invented by me?
Note that this function will only do one replacement. I’m looking for existing solutions that similarly replace a single occurrence, as well as those that replace all occurrences.
outis
74.4k21 gold badges149 silver badges219 bronze badges
asked Dec 29, 2011 at 14:05
12
Instead of a function that only replaces occurrences of one value in an array, there’s the more general array_map
:
array_map(function ($v) use ($value, $replacement) {
return $v == $value ? $replacement : $v;
}, $arr);
To replace multiple occurrences of multiple values using array of value => replacement:
array_map(function ($v) use ($replacement) {
return isset($replacement[$v]) ? $replacement[$v] : $v;
}, $arr);
To replace a single occurrence of one value, you’d use array_search
as you do. Because the implementation is so short, there isn’t much reason for the PHP developers to create a standard function to perform the task. Not to say that it doesn’t make sense for you to create such a function, if you find yourself needing it often.
answered Dec 29, 2011 at 14:19
outisoutis
74.4k21 gold badges149 silver badges219 bronze badges
5
While there isn’t one function equivalent to the sample code, you can use array_keys
(with the optional search value parameter), array_fill
and array_replace
to achieve the same thing:
EDIT by Tomas: the code was not working, corrected it:
$ar = array_replace($ar,
array_fill_keys(
array_keys($ar, $value),
$replacement
)
);
Tomas
56.6k48 gold badges232 silver badges368 bronze badges
answered Dec 29, 2011 at 14:09
Deept RaghavDeept Raghav
1,43013 silver badges14 bronze badges
5
If performance is an issue, one may consider not to create multiple functions within array_map()
. Note that isset()
is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
rmorse
7266 silver badges17 bronze badges
answered Sep 1, 2015 at 0:12
BurninLeoBurninLeo
4,1304 gold badges37 silver badges54 bronze badges
Try this function.
public function recursive_array_replace ($find, $replace, $array) {
if (!is_array($array)) {
return str_replace($find, $replace, $array);
}
$newArray = [];
foreach ($array as $key => $value) {
$newArray[$key] = recursive_array_replace($find, $replace, $value);
}
return $newArray;
}
Cheers!
Joshua
4,7642 gold badges30 silver badges44 bronze badges
answered Dec 29, 2011 at 14:13
Prasad RajapakshaPrasad Rajapaksha
6,05210 gold badges36 silver badges52 bronze badges
1
$ar[array_search('green', $ar)] = 'value';
answered Mar 11, 2019 at 14:26
2
Depending whether it’s the value, the key or both you want to find and replace on you could do something like this:
$array = json_decode( str_replace( $replace, $with, json_encode( $array ) ), true );
I’m not saying this is the most efficient or elegant, but nice and simple.
answered Sep 5, 2016 at 19:50
1
What about array_walk()
with callback?
$array = ['*pasta', 'cola', 'pizza'];
$search = '*';
$replace = '*';
array_walk($array,
function (&$v) use ($search, $replace){
$v = str_replace($search, $replace, $v);
}
);
print_r($array);
answered Sep 13, 2016 at 14:27
user3396065user3396065
5405 silver badges15 bronze badges
1
Based on Deept Raghav
‘s answer, I created the follow solution that does regular expression search.
$arr = [
'Array Element 1',
'Array Element 2',
'Replace Me',
'Array Element 4',
];
$arr = array_replace(
$arr,
array_fill_keys(
array_keys(
preg_grep('/^Replace/', $arr)
),
'Array Element 3'
)
);
echo '<pre>', var_export($arr), '</pre>';
PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt
answered Mar 4, 2016 at 22:45
1
PHP 8, a strict version to replace one string value into another:
array_map(static fn (string $value): string => $value === $find ? $replace : $value, $array);
An example — replace value foo
by bar
:
array_map(static fn (string $value): string => $value === 'foo' ? 'bar' : $value, $array);
answered Aug 9, 2021 at 20:38
1
You can make full string matches without specifying the keys of qualifying values, by calling preg_replace()
with a pattern containing start and end of string anchors (^
, $
). If your search term may contain characters which have a special meaning to the regex engine, then be sure to escape them with preg_quote()
to avoid breakage. While regex is not entirely called for, regex offers some very convenient ways to tweak the search term handling. (Demo)
function array_replace_value(&$ar, $value, $replacement)
{
$ar = preg_replace(
'/^' . preg_quote($value, '/') . '$/',
$replacement,
$ar
);
}
I might be more inclined to use array_map()
with arrow function syntax so that global variables can be accessed within the custom function scope. (Demo)
$needle = 'foo';
$newValue = 'bar';
var_export(
array_map(fn($v) => $v === $needle ? $newValue : $v, $array)
);
answered Dec 13, 2022 at 12:05
mickmackusamickmackusa
41.8k12 gold badges82 silver badges125 bronze badges
$ar = array(1,2,3,4,5,6,7,8);
$find = array(2,3);
$replace = array(13);
function update_bundle_package($ar,$find,$replace){
foreach ($find as $x => $y) {
///TO REMOVE PACKAGE
if (($key = array_search($y, $ar)) !== false) {
unset($ar[$key]);
}
///TO REMOVE PACKAGE
}
$ar = array_merge($ar, $replace);
}
answered Dec 22, 2022 at 8:34
1
<b>$green_key = array_search('green', $input); // returns the first key whose value is 'green'
$input[$green_key] = ‘apple’; // replace ‘green’ with ‘apple’
answered Dec 29, 2011 at 14:17
Muthu KrishnanMuthu Krishnan
1,6642 gold badges10 silver badges15 bronze badges
2
Как изменить значения элементов в массиве php
/ 👁 8665
В программировании в целом и при создании сайтов в частности нам все время приходится иметь дело с массивами.
Например, мы получаем данные из базы в виде массива и выводим их на сайт. Также мы можем собирать какие-то данные в массив и в последствии захотеть как-то их модифицировать.
Обычно, чтобы просто вывести данные из массива, достаточно пройтись по нему циклом, например foreach.
Однако, часто бывает так, что данные в массиве нам нужно изменить или как-то обработать.
Для этих задач можно также использовать цикл, но можно сделать это куда более элегантно и удобно, написав при этом меньше кода.
Сегодня рассмотрим, как применить какое-либо действие к каждому элементу массива.
Вариант 1. Изменяем элементы массива в цикле.
Для начала предлагаю создать массив и заполнить его.
Я не буду делать это вручную, а воспользуюсь циклом. Вот так.
<?php $my_array = []; for($i = 0; $i <= 9; $i++){ array_push($my_array, $i+1); } ?>
Если сейчас мы выведем наш массив на экран, то увидим следующее.
<pre> <?php print_r($my_array); ?> </pre>
Как видите, индексы массива начинаются с 0, в то время, как их значения начинаются с 1. В реальной же ситуации довольно часто значение индекса будет не соответствовать значению элемента. Кроме того, индексы в массиве вообще могут идти не по порядку. Об этом следует помнить.
Что если теперь мы захотим изменить каждый элемент массива, умножив его значение на 2.
Мы можем сделать это, воспользовавшись циклом foreach. Мы будем перебирать массив и умножать каждый его элемент на 2.
<?php $new_array = []; foreach($my_array as $item){ $new_array[] = $item * 2; } ?>
Выведем результат на экран.
<pre> <?php print_r($new_array); ?> </pre>
Мы получили нужный результат. Теперь давайте попробуем сделать то же самое, но с помощью функции array_map().
Вариант 2. Изменяем элементы массива при помощи array_map().
Эта функция принимает на вход несколько параметров:
- callback функцию, которая будет обрабатывать каждый элемент массива (можно передать имя функции, а можно прописать анонимную функцию в качестве передаваемого параметра);
- массив, элементы которого мы изменяем;
- дополнительные массивы для обработки callback-функцией (необязательный параметр).
Функция возвращает преобразованный массив. Если функции передается один массив, то ключи аргументов будут сохранены (что иногда может иметь большое значение).
Итак, давайте посмотрим, как это может выглядеть. В моем примере я не создаю отдельную callback-функцию, а передаю анонимную функцию в качестве аргумента.
<?php $new_array1 = array_map(function($n){ return ($n * 2); }, $my_array); ?>
Выведем результат на экран.
Получаем тот же самый результат. Однако, в этом варианте, даже если бы ключи элементов шли не по порядку, их значения были бы сохранены, в отличие от изменения значений элементов в цикле foreach.
На следующей картинке покажу вам разницу в результатах.
Разница в изменении значений элементов массива при использовании foreach и array_map(), когда ключи идут не по порядку.
Попробуйте проделать все это сами, чтобы прочувствовать результат.
Не ограничивайтесь перебором массивов в циклах, потому что для некоторых задач уже существуют специальные функции, которые решают эти задачи гораздо более эффективно.
До новых встреч в новых статьях. Понравилась статья? – Ставьте лайк, делитесь с друзьями, оставляйте комменты.
About The Author
Anna Kotelnikova
Как можно заменить значение в массиве по ключу с примерами
Как заменить значение массива по ключу, вообще в любом массиве. Приведем несколько вариантов смены значений по ключу в массиве! В разных видах массивов
Все способы замены значений по ключу в разных видах массивов
- Заменить значение по ключу в простом массиве
- Замена значения по ключу в любом массиве
- Заменить значение по ключу в в цикле
- Замена значения по ключу в ассоциативном массиве
Заменить значение по ключу в простом массиве
Для того, чтобы продемонстрировать замену значения по ключу в простом массиве нам потребуется:
Простой массив, в котором мы и будем менять значение ячейки массива по ключу
$example_simple_array = array(‘кошка’,’собака’,’корова’,’курица’,’слон’,’тигр’ );
Выведем данный массив прямо здесь через print_r
Array
(
[0] => кошка
[1] => собака
[2] => корова
[3] => курица
[4] => слон
[5] => тигр
)
Предположим, что нам требуется заменить значение ячейки массива в ключе номер 1, нам просто требуется этой ячейке присвоить новое значение:
$example_simple_array [1] = ‘таракан’;
После этой строки опять выводим наш массив и посмотрим, произошла ли замена значения по ключу в ячейке массива:
Array
(
[0] => кошка
[1] => таракан
[2] => корова
[3] => курица
[4] => слон
[5] => тигр
)
Как видим, наше значение в ячейки массива заменилось по ключу, как нам и требовалось
Замена значения по ключу в любом массиве
Как вы наверное знаете, что массивы бывают разными, как заменить значение ячейки массива в любом массиве!?
Я вам дам простой совет, как это сделать!
Самая главная проблема в такого рода заменах в том. что трудно бывает обратиться к ячейке массива, как мы видели выше, обратиться к ячейке простого массива достаточно просто:
$example_simple_array [1] = ‘таракан’;
В ассоциативных массивах и многомерных со сложной структурой, порой довольно трудно обратиться к ячейке, поэтому, прежде чем делать какие-то действия замены, просто выведите значение данной ячейки на экран. Для примера возьмем уже использованный нами многомерный массив
$переменная = array (
«Иванов» => array («рост» => 174, «вес» => 68),
«Петров» => array («рост» => 181, «вес» => 90),
«Сидоров» => array («рост» => 166, «вес» => 73));
Далее создаем путь до требуемой ячейки, и проверим с помощью вывода echo
echo $переменная[Иванов][вес];
Результат:
68
И раз у нас все прошло удачно, то теперь мы спокойно по данному ключу можем заменить значение в любом массиве
$переменная[Иванов][вес] =200;
И выведем результат замены значения по ключу в массиве:
Array
(
[Иванов] => Array
(
[рост] => 174
[вес] => 200
)
[Петров] => Array
(
[рост] => 181
[вес] => 90
)
[Сидоров] => Array
(
[рост] => 166
[вес] => 73
)
)
Как видим значение ячейки массива $переменная[Иванов][вес] изменилось на 200… тебе дружочек похудеть бы не мешало!
смайлы
Заменить значение по ключу в в цикле
Вообще на тему замены значения по ключу в массиве, довольно сложно что-то еще написать…
В жизни всякое случается и встречаются ситуации, что нужно в цикле по ключу заменить какое-то значение в массиве.
В зависимости от цикла, создаем условие, путь это будет цикл for:
for ($i=0; $i < count($array) ; $i++) {
if([$i] ==»
Искомый номер ключа…
«) { $array[$i] = «
Новое значение
«;}
}
Можете не благодарить, лучше помогите!
COMMENTS+
BBcode
array_replace
(PHP 5 >= 5.3.0, PHP 7)
array_replace — Замена элементов массива элементами других переданных массивов
Описание
array array_replace
( array $array1
, array $array2
[, array $...
] )
array_replace() замещает значения массива
array1
значениями с такими же ключами из
других переданных массивов. Если ключ из первого массива присутствует
во втором массиве, его значение заменяется на значение из второго массива.
Если ключ есть во втором массиве, но отсутствует в первом — он будет создан
в первом массиве. Если ключ присутствует только в первом массиве, то
сохранится как есть. Если для замены передано несколько массивов, они
будут обработаны в порядке передачи и более поздние массивы будут
перезаписывать значения из предыдущих.
array_replace() не рекурсивная: значения первого массива
будут заменены вне зависимости от типа значений второго массива, даже если
это будут вложенные массивы.
Список параметров
-
array1
-
Массив, элементы которого требуется заменить.
-
array2
-
Массив, элементами которого будут заменяться элементы первого массива.
-
...
-
Еще массивы, из которых будут браться элементы для замены.
Значения следующего массива затирают значения предыдущего.
Возвращаемые значения
Возвращает массив (array) или NULL
в случае ошибки.
Примеры
Пример #1 Пример использования array_replace()
<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>
Результат выполнения данного примера:
Array ( [0] => grape [1] => banana [2] => apple [3] => raspberry [4] => cherry )
Смотрите также
- array_replace_recursive() — Рекурсивно заменяет элементы первого массива элементами переданных массивов
- array_merge() — Сливает один или большее количество массивов
Вернуться к: Функции для работы с массивами
Массивы
На самом деле массив в PHP — это упорядоченное отображение, которое устанавливает
соответствие между значением и ключом.
Этот тип оптимизирован в нескольких направлениях, поэтому вы можете использовать его как
собственно массив, список (вектор), хеш-таблицу (являющуюся реализацией карты), словарь,
коллекцию, стек, очередь и, возможно, что-то ещё. Так как значением массива может быть
другой массив PHP, можно также создавать деревья и многомерные массивы.
Объяснение этих структур данных выходит за рамки данного
справочного руководства, но вы найдёте как минимум один пример по
каждой из них. За дополнительной информацией вы можете обратиться к
соответствующей литературе по этой обширной теме.
Синтаксис
Определение при помощи array()
Массив (тип array) может быть создан языковой конструкцией array().
В качестве параметров она принимает любое количество разделённых запятыми пар
key => value
(ключ => значение).
array( key => value, key2 => value2, key3 => value3, ... )
Запятая после последнего элемента массива необязательна и может быть опущена.
Обычно это делается для однострочных массивов, то есть array(1, 2)
предпочтительней array(1, 2, )
. Для многострочных массивов с другой
стороны обычно используется завершающая запятая, так как позволяет легче добавлять
новые элементы в конец массива.
Замечание:
Существует короткий синтаксис массива, который заменяет
array()
на[]
.
Пример #1 Простой массив
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);// Использование синтаксиса короткого массива
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
key может быть либо типа int, либо типа
string. value может быть любого типа.
Дополнительно с ключом key будут сделаны следующие преобразования:
-
Строки (string), содержащие целое число (int) (исключая случаи, когда число предваряется знаком+
) будут преобразованы к типу int.
Например, ключ со значением"8"
будет в действительности сохранён со
значением8
. С другой стороны, значение"08"
не
будет преобразовано, так как оно не является корректным десятичным целым.
-
Числа с плавающей точкой (float) также будут преобразованы к типу
int, то есть дробная часть будет отброшена. Например, ключ со значением
8.7
будет в действительности сохранён со значением8
.
-
Тип bool также преобразовываются к типу int.
Например, ключ со значениемtrue
будет сохранён со значением
1
и ключ со значениемfalse
будет сохранён со
значением0
.
-
Тип null будет преобразован к пустой строке. Например, ключ со
значениемnull
будет в действительности сохранён со значением
""
.
-
Массивы (array) и объекты (object) не
могут использоваться в качестве ключей. При подобном использовании будет
генерироваться предупреждение:Недопустимый тип смещения (Illegal offset type)
.
Если несколько элементов в объявлении массива используют одинаковый ключ, то только
последний будет использоваться, а все другие будут перезаписаны.
Пример #2 Пример преобразования типов и перезаписи элементов
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
Результат выполнения данного примера:
array(1) { [1]=> string(1) "d" }
Так как все ключи в вышеприведённом примере преобразуются к 1
,
значение будет перезаписано на каждый новый элемент и останется только последнее
присвоенное значение "d"
.
Массивы в PHP могут содержать ключи типов int и string
одновременно, так как PHP не делает различия между индексированными и ассоциативными
массивами.
Пример #3 Смешанные ключи типов int и string
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
Результат выполнения данного примера:
array(4) { ["foo"]=> string(3) "bar" ["bar"]=> string(3) "foo" [100]=> int(-100) [-100]=> int(100) }
Параметр key является необязательным. Если он не указан,
PHP будет использовать предыдущее наибольшее значение ключа типа
int, увеличенное на 1.
Пример #4 Индексированные массивы без ключа
<?php
$array = array("foo", "bar", "hallo", "world");
var_dump($array);
?>
Результат выполнения данного примера:
array(4) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(5) "hallo" [3]=> string(5) "world" }
Возможно указать ключ только для некоторых элементов и пропустить для других:
Пример #5 Ключи для некоторых элементов
<?php
$array = array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>
Результат выполнения данного примера:
array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [6]=> string(1) "c" [7]=> string(1) "d" }
Как вы видите последнее значение "d"
было присвоено ключу
7
. Это произошло потому, что самое большое значение ключа целого
типа перед этим было 6
.
Пример #6 Расширенный пример преобразования типов и перезаписи элементов
<?php
$array = array(
1 => 'a',
'1' => 'b', // значение "b" перезапишет значение "a"
1.5 => 'c', // значение "c" перезапишет значение "b"
-1 => 'd',
'01' => 'e', // поскольку это не целочисленная строка, она НЕ перезапишет ключ для 1
'1.5' => 'f', // поскольку это не целочисленная строка, она НЕ перезапишет ключ для 1
true => 'g', // значение "g" перезапишет значение "c"
false => 'h',
'' => 'i',
null => 'j', // значение "j" перезапишет значение "i"
'k', // значение "k" присваивается ключу 2. Потому что самый большой целочисленный ключ до этого был 1
2 => 'l', // значение "l" перезапишет значение "k"
);var_dump($array);
?>
Результат выполнения данного примера:
array(7) { [1]=> string(1) "g" [-1]=> string(1) "d" ["01"]=> string(1) "e" ["1.5"]=> string(1) "f" [0]=> string(1) "h" [""]=> string(1) "j" [2]=> string(1) "l" }
Этот пример включает все вариации преобразования ключей и перезаписи элементов
Доступ к элементам массива с помощью квадратных скобок
Доступ к элементам массива может быть осуществлён с помощью синтаксиса array[key]
.
Пример #7 Доступ к элементам массива
<?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" int(24) string(3) "foo"
Замечание:
До PHP 8.0.0 квадратные и фигурные скобки могли использоваться взаимозаменяемо для доступа
к элементам массива (например, в примере выше$array[42]
и$array{42}
делали то же самое).
Синтаксис фигурных скобок устарел в PHP 7.4.0
и больше не поддерживается в PHP 8.0.0.
Пример #8 Разыменование массива
<?php
function getArray() {
return array(1, 2, 3);
}$secondElement = getArray()[1];
?>
Замечание:
Попытка доступа к неопределённому ключу в массиве — это то же самое,
что и попытка доступа к любой другой неопределённой переменной:
будет сгенерирована ошибка уровняE_WARNING
(ошибка уровняE_NOTICE
до PHP 8.0.0),
и результат будетnull
.
Замечание:
Массив, разыменовывающий скалярное значение, которое не является строкой
(string), отдастnull
. До PHP 7.4.0 не выдаётся сообщение об ошибке.
Начиная с PHP 7.4.0, выдаётся ошибкаE_NOTICE
;
с PHP 8.0.0 выдаётся ошибкаE_WARNING
.
Создание/модификация с помощью синтаксиса квадратных скобок
Существующий массив может быть изменён путём явной установкой значений в нем.
Это выполняется присвоением значений массиву (array) с указанием в
скобках ключа. Кроме того, ключ можно опустить, в результате получится пустая пара скобок ([]
).
$arr[key] = value; $arr[] = value; // key может быть int или string // value может быть любым значением любого типа
Если массив $arr ещё не существует или для него
задано значение null
или false
, он будет создан.
Таким образом, это ещё один способ определить массив array. Однако такой
способ применять не рекомендуется, так как если переменная $arr
уже содержит некоторое значение (например, значение типа string из
переменной запроса), то это значение останется на месте и []
может на
самом деле означать доступ к символу в
строке. Лучше инициализировать переменную путём явного присваивания значения.
Замечание:
Начиная с PHP 7.1.0, используя в оператор «пустой индекс» на строке, приведёт к
фатальной ошибке. Ранее, в этом случае, строка молча преобразовывалась в массив.
Замечание:
Начиная с PHP 8.1.0, создание нового массива с помощью значенияfalse
устарело.
Создание нового массива изnull
и неопределённого значения по-прежнему разрешено.
Для изменения определённого значения просто присвойте новое значение элементу,
используя его ключ. Если вы хотите удалить пару ключ/значение, вам необходимо
использовать функцию unset().
<?php
$arr = array(5 => 1, 12 => 2);$arr[] = 56; // В этом месте скрипта это
// то же самое, что и $arr[13] = 56;$arr["x"] = 42; // Это добавляет к массиву новый
// элемент с ключом "x"unset($arr[5]); // Это удаляет элемент из массиваunset($arr); // Это удаляет массив полностью
?>
Замечание:
Как уже говорилось выше, если ключ не был указан, то будет взят максимальный из
существующих целочисленных (int) индексов, и новым ключом будет
это максимальное значение (в крайнем случае 0) плюс 1. Если целочисленных (int) индексов
ещё нет, то ключом будет0
(ноль).Учтите, что максимальное целое значение ключа не обязательно
существует в массиве в данный момент. Оно могло просто существовать
в массиве какое-то время, с тех пор как он был переиндексирован в последний раз.
Следующий пример это иллюстрирует:
<?php
// Создаём простой массив.
$array = array(1, 2, 3, 4, 5);
print_r($array);// Теперь удаляем каждый элемент, но сам массив оставляем нетронутым:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);// Добавляем элемент (обратите внимание, что новым ключом будет 5, вместо 0).
$array[] = 6;
print_r($array);// Переиндексация:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>
Результат выполнения данного примера:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
Деструктуризация массива
Массивы могут быть деструктурированы с помощью языковых конструкций []
(начиная с PHP 7.1.0)
или list(). Эти конструкции могут быть использованы для деструктуризации массива на отдельные переменные.
<?php
$source_array = ['foo', 'bar', 'baz'];
[$foo, $bar, $baz] = $source_array;
echo $foo; // выведет "foo"
echo $bar; // выведет "bar"
echo $baz; // выведет "baz"
?>
Деструктуризация массива может быть использована в конструкции foreach
для деструктуризации многомерного массива во время итерации по нему.
<?php
$source_array = [
[1, 'John'],
[2, 'Jane'],
];
foreach ($source_array as [$id, $name]) {
// логика работы с $id и $name
}
?>
Элементы массива будут игнорироваться, если переменная не указана.
Деструктуризация массива всегда начинается с индекса 0
.
<?php
$source_array = ['foo', 'bar', 'baz'];// Присваивание элементу с индексом 2 переменной $baz
[, , $baz] = $source_array;
echo
$baz; // выведет "baz"
?>
Начиная с PHP 7.1.0, ассоциативные массивы также могут быть деструктурированы.
Это позволяет легче выбирать нужный элемент в массивах с числовым индексом,
так как индекс может быть указан явно.
<?php
$source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3];// Присваивание элементу с индексом 'baz' переменной $three
['baz' => $three] = $source_array;
echo
$three; // выведет 3$source_array = ['foo', 'bar', 'baz'];// Присваивание элементу с индексом 2 переменной $baz
[2 => $baz] = $source_array;
echo
$baz; // выведет "baz"
?>
Деструктуризация массива может быть использована для простой замены двух переменных местами.
<?php
$a = 1;
$b = 2;
[$b, $a] = [$a, $b];
echo $a; // выведет 2
echo $b; // выведет 1
?>
Замечание:
Оператор
...
не поддерживается в присваиваниях.
Замечание:
Попытка получить доступ к ключу массива, который не был определён,
аналогична обращению к любой другой неопределённой переменной:
будет выдано сообщение об ошибке уровняE_WARNING
(ошибка уровняE_NOTICE
до PHP 8.0.0),
а результатом будетnull
.
Полезные функции
Для работы с массивами существует достаточное количество полезных
функций. Смотрите раздел функции для работы
с массивами.
Замечание:
Функция unset() позволяет удалять ключи массива.
Обратите внимание, что массив НЕ
будет переиндексирован. Если вы действительно хотите поведения в стиле
«удалить и сдвинуть», можно переиндексировать массив
используя array_values().
<?php
$a = array(1 => 'один', 2 => 'два', 3 => 'три');
unset($a[2]);
/* даст массив, представленный так:
$a = array(1 => 'один', 3 => 'три');
а НЕ так:
$a = array(1 => 'один', 2 => 'три');
*/$b = array_values($a);
// Теперь $b это array(0 => 'один', 1 => 'три')
?>
Управляющая конструкция foreach существует специально для массивов.
Она предоставляет возможность легко пройтись по массиву.
Что можно и нельзя делать с массивами
Почему $foo[bar]
неверно?
Всегда заключайте в кавычки строковый литерал в индексе ассоциативного массива.
К примеру, пишите $foo['bar']
, а не
$foo[bar]
. Но почему? Часто в старых скриптах можно встретить
следующий синтаксис:
<?php
$foo[bar] = 'враг';
echo $foo[bar];
// и т.д.
?>
Это неверно, хотя и работает. Причина в том, что этот код содержит неопределённую
константу (bar
), а не строку ('bar'
— обратите внимание
на кавычки). Это работает, потому что PHP автоматически преобразует
«голую строку» (не заключённую в кавычки строку,
которая не соответствует ни одному из известных символов языка) в строку
со значением этой «голой строки». Например, если константа с именем bar
не определена, то PHP заменит bar на
строку 'bar'
и использует её.
Внимание
Резервный вариант для обработки неопределённой константы как пустой строки вызывает ошибку уровня E_NOTICE
.
Начиная с PHP 7.2.0 поведение объявлено устаревшим и вызывает ошибку уровня E_WARNING
.
Начиная с PHP 8.0.0, удалено и выбрасывает исключение Error.
Замечание:
Это не означает, что нужно всегда заключать
ключ в кавычки. Нет необходимости заключать в кавычки константы или переменные, поскольку это
помешает PHP обрабатывать их.
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Простой массив:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "nПроверяем $i: n";
echo "Плохо: " . $array['$i'] . "n";
echo "Хорошо: " . $array[$i] . "n";
echo "Плохо: {$array['$i']}n";
echo "Хорошо: {$array[$i]}n";
}
?>
Результат выполнения данного примера:
Проверяем 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Плохо: Хорошо: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Плохо: Хорошо: 1 Проверяем 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Плохо: Хорошо: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Плохо: Хорошо: 2
Дополнительные примеры, демонстрирующие этот факт:
<?php
// Показываем все ошибки
error_reporting(E_ALL);$arr = array('fruit' => 'apple', 'veggie' => 'carrot');// Верно
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Неверно. Это работает, но из-за неопределённой константы с
// именем fruit также вызывает ошибку PHP уровня E_NOTICE
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// Давайте определим константу, чтобы продемонстрировать, что
// происходит. Мы присвоим константе с именем fruit значение 'veggie'.
define('fruit', 'veggie');// Теперь обратите внимание на разницу
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// Внутри строки это нормально. Внутри строк константы не
// рассматриваются, так что ошибки E_NOTICE здесь не произойдёт
print "Hello $arr[fruit]"; // Hello apple
// С одним исключением: фигурные скобки вокруг массивов внутри
// строк позволяют константам там находиться
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// Это не будет работать и вызовет ошибку обработки, такую как:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// Это, конечно, также действует и с суперглобальными переменными в строках
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";// Ещё одна возможность - конкатенация
print "Hello " . $arr['fruit']; // Hello apple
?>
Если вы переведёте error_reporting
в режим отображения ошибок уровня
E_NOTICE
(например, такой как
E_ALL
), вы сразу увидите эти ошибки. По
умолчанию
error_reporting установлена их не отображать.
Как указано в разделе синтаксис,
внутри квадратных скобок (‘[
‘
и ‘]
‘) должно быть выражение. Это означает, что можно писать вот так:
<?php
echo $arr[somefunc($bar)];
?>
Это пример использования возвращаемого функцией значения
в качестве индекса массива. PHP известны также и константы:
<?php
$error_descriptions[E_ERROR] = "Произошла фатальная ошибка";
$error_descriptions[E_WARNING] = "PHP сообщает о предупреждении";
$error_descriptions[E_NOTICE] = "Это лишь неофициальное замечание";
?>
Обратите внимание, что E_ERROR
— это такой же
верный идентификатор, как и bar
в первом примере.
Но последний пример по сути эквивалентен такой записи:
<?php
$error_descriptions[1] = "Произошла фатальная ошибка";
$error_descriptions[2] = "PHP сообщает о предупреждении";
$error_descriptions[8] = "Это лишь неофициальное замечание";
?>
поскольку E_ERROR
соответствует 1
и т.д.
Так что же в этом плохого?
Когда-нибудь в будущем команда разработчиков PHP возможно пожелает
добавить ещё одну константу или ключевое слово, либо константа из
другого кода может вмешаться и тогда у вас могут
возникнуть проблемы. Например, вы уже не можете использовать таким
образом слова empty
и
default
, поскольку они являются
зарезервированными ключевыми словами.
Замечание:
Повторим, внутри строки (string), заключённой
в двойные кавычки, корректно не окружать индексы
массива кавычками, поэтому"$foo[bar]"
является верной записью. Более подробно почему — смотрите
вышеприведённые примеры, а также раздел по
обработке
переменных в строках.
Преобразование в массив
Для любого из типов int, float,
string, bool и resource,
преобразование значения в массив даёт результатом массив с
одним элементом (с индексом 0), являющимся скалярным значением, с
которого вы начали. Другими словами, (array)$scalarValue
— это точно то же самое, что и array($scalarValue)
.
Если вы преобразуете в массив объект (object), вы
получите в качестве элементов массива свойства (переменные-члены)
этого объекта. Ключами будут имена переменных-членов, с некоторыми примечательными
исключениями: целочисленные свойства станут недоступны;
к закрытым полям класса (private) спереди будет дописано имя класса;
к защищённым полям класса (protected) спереди будет добавлен символ ‘*’.
Эти добавленные значения с обоих сторон также имеют NUL
байты.
Неинициализированные типизированные свойства
автоматически отбрасываются.
<?php
class A {
private $B;
protected $C;
public $D;
function __construct()
{
$this->{1} = null;
}
}
var_export((array) new A());
?>
Результат выполнения данного примера:
array ( '' . "" . 'A' . "" . 'B' => NULL, '' . "" . '*' . "" . 'C' => NULL, 'D' => NULL, 1 => NULL, )
Это может вызвать несколько неожиданное поведение:
<?php
class A {
private $A; // Это станет 'AA'
}
class B extends A {
private $A; // Это станет 'BA'
public $AA; // Это станет 'AA'
}
var_dump((array) new B());
?>
Результат выполнения данного примера:
array(3) { ["BA"]=> NULL ["AA"]=> NULL ["AA"]=> NULL }
Вышеприведённый код покажет 2 ключа с именем ‘AA’, хотя один из них на самом деле
имеет имя ‘AA’.
Если вы преобразуете в массив значение null
, вы получите
пустой массив.
Распаковка массива
Массив с префиксом ...
будет распакован во время определения массива.
Только массивы и объекты, которые реализуют интерфейс Traversable, могут быть распакованы.
Распаковка массива с помощью ...
доступна, начиная с PHP 7.4.0.
Массив можно распаковывать несколько раз и добавлять обычные элементы до или после оператора ...
:
Пример #9 Простая распаковка массива
<?php
// Использование короткого синтаксиса массива.
// Также работает с синтаксисом array().
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; // [1, 2, 3]
$arr3 = [0, ...$arr1]; // [0, 1, 2, 3]
$arr4 = [...$arr1, ...$arr2, 111]; // [1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; // [1, 2, 3, 1, 2, 3]
function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c' => 'd']; // ['a', 'b', 'c' => 'd']
?>
Распаковка массива с помощью оператора ...
следует семантике функции array_merge().
То есть более поздние строковые ключи перезаписывают более ранние, а целочисленные ключи перенумеровываются:
Пример #10 Распаковка массива с дублирующим ключом
<?php
// строковый ключ
$arr1 = ["a" => 1];
$arr2 = ["a" => 2];
$arr3 = ["a" => 0, ...$arr1, ...$arr2];
var_dump($arr3); // ["a" => 2]
// целочисленный ключ
$arr4 = [1, 2, 3];
$arr5 = [4, 5, 6];
$arr6 = [...$arr4, ...$arr5];
var_dump($arr6); // [1, 2, 3, 4, 5, 6]
// Который [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6]
// где исходные целочисленные ключи не были сохранены.
?>
Замечание:
Ключи, которые не являются ни целыми числами, ни строками, вызывают ошибку TypeError.
Такие ключи могут быть сгенерированы только объектом Traversable.
Замечание:
До PHP 8.1 распаковка массива со строковым ключом не поддерживалась:
<?php
$arr1 = [1, 2, 3];
$arr2 = ['a' => 4];
$arr3 = [...$arr1, ...$arr2];
// Ошибка: невозможно распаковать массив со строковыми ключами в example.php:5
$arr4 = [1, 2, 3];
$arr5 = [4, 5];
$arr6 = [...$arr4, ...$arr5]; // работает. [1, 2, 3, 4, 5]
?>
Примеры
Тип массив в PHP является очень гибким, вот несколько примеров:
<?php
// это
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // ключом будет 0
);$b = array('a', 'b', 'c');// . . .полностью соответствует
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // ключом будет 0$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';// после выполнения этого кода, $a будет массивом
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), а $b будет
// array(0 => 'a', 1 => 'b', 2 => 'c'), или просто array('a', 'b', 'c').
?>
Пример #11 Использование array()
<?php
// Массив как карта (свойств)
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);// исключительно числовые ключи
$array = array( 7,
8,
0,
156,
-10
);
// это то же самое, что и array(0 => 7, 1 => 8, ...)$switching = array( 10, // ключ = 0
5 => 6,
3 => 7,
'a' => 4,
11, // ключ = 6 (максимальным числовым индексом было 5)
'8' => 2, // ключ = 8 (число!)
'02' => 77, // ключ = '02'
0 => 12 // значение 10 будет перезаписано на 12
);// пустой массив
$empty = array();
?>
Пример #12 Коллекция
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach (
$colors as $color) {
echo "Вам нравится $color?n";
}?>
Результат выполнения данного примера:
Вам нравится red? Вам нравится blue? Вам нравится green? Вам нравится yellow?
Изменение значений массива напрямую возможно
путём передачи их по ссылке.
Пример #13 Изменение элемента в цикле
<?php
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* это нужно для того, чтобы последующие записи в
$color не меняли последний элемент массива */print_r($colors);
?>
Результат выполнения данного примера:
Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW )
Следующий пример создаёт массив, начинающийся с единицы.
Пример #14 Индекс, начинающийся с единицы
<?php
$firstquarter = array(1 => 'Январь', 'Февраль', 'Март');
print_r($firstquarter);
?>
Результат выполнения данного примера:
Array ( [1] => 'Январь' [2] => 'Февраль' [3] => 'Март' )
Пример #15 Заполнение массива
<?php
// заполняем массив всеми элементами из директории
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
Массивы упорядочены. Вы можете изменять порядок элементов,
используя различные функции сортировки. Для дополнительной
информации смотрите раздел функции
для работы с массивами. Вы можете подсчитать количество
элементов в массиве с помощью функции count().
Пример #16 Сортировка массива
<?php
sort($files);
print_r($files);
?>
Поскольку значение массива может быть чем угодно, им также
может быть другой массив. Таким образом вы можете создавать
рекурсивные и многомерные массивы.
Пример #17 Рекурсивные и многомерные массивы
<?php
$fruits = array ( "fruits" => array ( "a" => "апельсин",
"b" => "банан",
"c" => "яблоко"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "первая",
5 => "вторая",
"третья"
)
);// Несколько примеров доступа к значениям предыдущего массива
echo $fruits["holes"][5]; // напечатает "вторая"
echo $fruits["fruits"]["a"]; // напечатает "апельсин"
unset($fruits["holes"][0]); // удалит "первая"
// Создаст новый многомерный массив
$juices["apple"]["green"] = "good";
?>
Обратите внимание, что при присваивании массива всегда
происходит копирование значения. Чтобы скопировать массив по
ссылке, вам нужно использовать оператор ссылки.
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 изменился,
// $arr1 всё ещё array(2, 3)$arr3 = &$arr1;
$arr3[] = 4; // теперь $arr1 и $arr3 одинаковы
?>
thomas tulinsky ¶
6 years ago
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"
liberchen at gmail dot com ¶
5 years ago
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 offset
You have to change to as below:
$a=array();
$a['a']=array(); // Declare it is an array first
$a['a']['b']='';
ken underscore yap atsign email dot com ¶
15 years ago
"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); ?>
Voila.
chris at ocportal dot com ¶
9 years ago
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']; // Outputs "changed"
?>
This can be useful in some cases, for example saving RAM within complex structures.
jeff splat codedread splot com ¶
17 years ago
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 )
Yesterday php'er ¶
5 years ago
--- 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...
ia [AT] zoznam [DOT] sk ¶
17 years ago
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:
<?php
foreach ( $arr as $key => &$value )
{
$value = 1;
}// without next line you can get bad results...
//unset( $value );$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:
<?php
foreach ( $arr as $key => $value )
{
$arr[ $key ] = 1;
}
?>
phplatino at gmail dot com ¶
1 year ago
to know the depth (dimension) of a ARRAY, you can use this:
function Dim_Ar($A, $i){
if(!is_array($A))return 0;
$t[] = 1;
foreach($A AS $e)if(is_array($e))$t[] = Dim_Ar($e, ++ $i) + 1;
return max($t);
}
and use with:
$Q = ARRAY(ARRAY(ARRAY()), ARRAY(ARRAY()));// here depth/dimension is three
echo Dim_Ar($Q, 0);
anisgazig at gmail dot com ¶
4 years ago
//array keys are always integer and string data type and array values are all data type
//type casting and overwriting(data type of array key)
//----------------------------------------------------
$arr = array(
1=>"a",//int(1)
"3"=>"b",//int(3)
"08"=>"c",//string(2)"08"
"80"=>"d",//int(80)
"0"=>"e",//int(0)
"Hellow"=>"f",//string(6)"Hellow"
"10Hellow"=>"h",//string(8)"10Hellow"
1.5=>"j",//int(1.5)
"1.5"=>"k",//string(3)"1.5"
0.0=>"l",//int(0)
false=>"m",//int(false)
true=>"n",//int(true)
"true"=>"o",//string(4)"true"
"false"=>"p",//string(5)"false"
null=>"q",//string(0)""
NULL=>"r",//string(0)"" note null and NULL are same
"NULL"=>"s",//string(4)"NULL" ,,,In last element of multiline array,comma is better to used.
);
//check the data type name of key
foreach ($arr as $key => $value) {
var_dump($key);
echo "<br>";
}
//NOte :array and object data type in keys are Illegal ofset.......
caifara aaaat im dooaat be ¶
17 years ago
[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 http://php.net/foreach 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:
<?php
$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 );
/* nothing changed result is:
Array
(
[0] => Array
(
[a] => 0
[b] => 1
)
[1] => Array
(
[aa] => 0
[bb] => 11
)
) */
foreach( $together as $key => $value ) {
$together[$key]["c"] = 3 ;
}
print_r( $together );
/* now it works, this prints
Array
(
[0] => Array
(
[a] => 0
[b] => 1
[c] => 3
)
[1] => Array
(
[aa] => 0
[bb] => 11
[c] => 3
)
)
*/
?>
ivail89 at mail dot ru ¶
2 years ago
Function unset can delete array's element by reference only when you specify source array. See example:
<?php
$array = [1, 2, 3, 4, 5];
foreach ($array as $k => &$v){
if ($k >= 3){
unset($v);
}
}
echo count($array); // 5
?>
In this case unset delete only reference, however original array didn't change.
Or different example:
<?php
$arr = [1, 2];
$a = &$arr[0];
unset($a);
count($arr); // 2
?>
So for deleting element from first example need use key and array.
<?php
// ...
unset($array[$k]);
// ...
?>
lars-phpcomments at ukmix dot net ¶
17 years ago
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');
?>
Denise Ignatova ¶
5 years ago
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 23
but :
$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
dylanfj700 at gmail dot com ¶
2 years ago
// Before php 5.4
$array = array(1,2,3);
// since php 5.4 , short syntax
$array = [1,2,3];
// I recommend using the short syntax if you have php version >= 5.4
note dot php dot lorriman at spamgourmet dot org ¶
9 years ago
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 :
http://uk3.php.net/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).
magraden86 at gmail dot com ¶
1 month ago
"Additionally the following key casts will occur: Floats are also cast to ints, which means that the fractional part will be truncated."
PHP 8.1 will show the following warning: "Deprecated: Implicit conversion from float ... to int loses precision in ..."
tissus ¶
4 years ago
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
);
Anonymous ¶
3 years ago
Wrappers for (array), returns array with normalize keys (without prefix):
<?php
function to_array_recursive($value): array
{
if (! is_object($value)) {
return (array) $value;
}
$class = get_class($value);
$arr = [];
foreact ((array) $value as $key => $val) {
$key = str_replace(["*", "{$class}"], '', $key);
$arr[$key] = is_object($val) ? to_array_recursive($val) : $val;
}
return $arr;
}
function
to_array($value): array
{
$arr = (array) $value;
if (! is_object($value)) {
return $arr;
}
$class = get_class($value);
$keys = str_replace(["*", "{$class}"], '', array_keys($arr));
return array_combine($keys, $arr);
}
?>
Demo:
<?php
class Test
{
protected $var = 1;
protected $var2;
private $TestVar = 3;
public function
__construct($isParent = true)
{
if ($isParent) {
$this->var2 = new self(! $isParent);
}
}
}$obj = new Test();
var_dump((array) $obj, to_array_recursive($obj));
?>
Walter Tross ¶
12 years ago
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.
ivegner at yandex dot ru ¶
9 years ago
Note that objects of classes extending ArrayObject SPL class are treated as arrays, and not as objects when converting to array.
<?php
class ArrayObjectExtended extends ArrayObject
{
private $private = 'private';
public $hello = 'world';
}$object = new ArrayObjectExtended();
$array = (array) $object;// This will not expose $private and $hello properties of $object,
// but return an empty array instead.
var_export($array);
?>