Home > Article > Backend Development > Comparison of array_replace, array_splice and str_replace functions in php
We know that there are some functions in PHP with similar functions or similar names, such as array_replace, array_splice and str_replace. Judging from the names, the first two operate on arrays, and the latter One that operates on strings.
The details are as follows:
array_replace function
<?php $arr1 = ['a' => 1, 'b' => 2, 'c' => 3]; $arr2 = ['b' => 4, 'c' => 5, 3]; $arr3 = [1, 2, 3]; $arr4 = array_replace($arr1, $arr2, $arr3); print_r($arr4); //Array //( // [a] => 1 // [b] => 4 // [c] => 5 // [0] => 1 // [1] => 2 // [2] => 3 //)
In this example, $arr3 and $arr2 have elements with the same key, so $arr3 $arr2 is replaced with different additions, and a temporary array is obtained. The temporary array ['b' => 4, 'c' => 5, 1,2,3] has elements with the same key as $arr1, so this temporary The array replaces $arr1, adds elements with different keys to $arr1, and finally returns the result array.
(Free learning video tutorial recommendation: php video tutorial)
<?php $arr1 = [1, 2, 3]; $arr2 = [1, 2, 3]; $arr3 = [1, 2, 3]; $arr4 = array_replace($arr1, $arr2, $arr3); print_r($arr4); //Array ////( //// [0] => 1 //// [1] => 2 //// [2] => 3 ////)
In this example, $arr3 replaces the same elements in $arr2, and then the resulting temporary array replaces $ Elements with the same key in arr1 are replaced.
array_splice function
<?php $arr1 = [1, 2, 3]; $arr2 = [1, 2, 3]; $arr3 = array_splice($arr1, 1, 2, $arr2); print_r($arr3); print_r($arr1); //Array //( // [0] => 2 // [1] => 3 //) //Array //( // [0] => 1 // [1] => 1 // [2] => 2 // [3] => 3 //)
This function cuts off the elements at $arr1, index 1, index 2, position, and then adds $arr2 to the remaining $arr1 After the element, this function affects the original array $arr1
str_replace function
<?php $str1 = 'abcde'; $str2 = 'ddddddddddd'; $str3 = str_replace('c',$str2,$str1); print_r($str1."\n"); print_r($str3); //abcde //abdddddddddddde
finds the position of character c in $str1 and replaces it with $str2. The original string is not affected.
Three functions, array_replace and stt_replace, although their function names are very similar, their functions are easily confused.
Recommended related articles and tutorials: php tutorial
The above is the detailed content of Comparison of array_replace, array_splice and str_replace functions in php. For more information, please follow other related articles on the PHP Chinese website!