PHP Doku:: Replaces elements from passed arrays into the first array - function.array-replace.html

Verlauf / Chronik / History: (3) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenArraysArray Funktionenarray_replace

Ein Service von Reinhard Neidl - Webprogrammierung.

Array Funktionen

<<array_replace_recursive

array_reverse>>

array_replace

(PHP 5 >= 5.3.0)

array_replaceReplaces elements from passed arrays into the first array

Beschreibung

array array_replace ( array &$array , array &$array1 [, array &$array2 [, array &$... ]] )

array_replace() replaces the values of the first array with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.

array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.

Parameter-Liste

array

The array in which elements are replaced.

array1

The array from which elements will be extracted.

Rückgabewerte

Returns an array, or NULL if an error occurs.

Beispiele

Beispiel #1 array_replace() example

<?php
$base 
= array("orange""banana""apple""raspberry");
$replacements = array(=> "pineapple"=> "cherry");
$replacements2 = array(=> "grape");

$basket array_replace($base$replacements$replacements2);
print_r($basket);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

Siehe auch


5 BenutzerBeiträge:
- Beiträge aktualisieren...
polecat at p0lecat dot com
29.11.2010 19:02
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.
polecat at p0lecat dot com
29.11.2010 18:57
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.
mail at romansklenar dot cz
11.12.2009 4:01
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...
tufan dot oezduman at googlemail dot com
6.11.2009 13:19
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
)
dyer85 at gmail dot com
29.07.2009 6:45
For a backward compatible alternative, you might try something like this:

<?php

if (!function_exists('array_replace'))
{
  function
array_replace( array &$array, array &$array1 )
  {
   
$args = func_get_args();
   
$count = func_num_args();

    for (
$i = 0; $i < $count; ++$i) {
      if (
is_array($args[$i])) {
        foreach (
$args[$i] as $key => $val) {
         
$array[$key] = $val;
        }
      }
      else {
       
trigger_error(
         
__FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
         
E_USER_WARNING
       
);
        return
NULL;
      }
    }

    return
$array;
  }
}

?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)