search and replace value in PHP array
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
)
);
How to replace array values according to a value replace map in PHP?
$origin = ['value1', 'value2', 'value3', '-2'];
$replace_map = [
'value1' => 'replace1',
'value2' => 'replace2',
'value8' => 'replace8',
2 => 77
];
$new = array_map(function($i) use($replace_map) {
return preg_replace_callback('/^(-)*(.+)$/',
function($m) use($replace_map) {
if(!isset($replace_map[$m[2]]))
return($m[0]);
return $m[1] . $replace_map[$m[2]];
},$i);
}, $origin);
print_r($new);
result
Array
(
[0] => replace1
[1] => replace2
[2] => value3
[3] => -77
)
Search and replace inside an associative array
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1') $myarray[$key] = 'search4';
}
Simple way to replace value in array in PHP when you know the index
To initialize an Array you have to use [] or the function array:
In your example:
$myarray = array();
If you want to add a series of values with the default key assignment you only have to put in between the parenthesis: array(color1, color2, color3)
$myarray = array('blue', 'red', 'yellow')
Then you can view what is on your variable, using: print_r($myarray)
print_r($myarray)
// this will output:
Array
(
[0] => blue
[1] => red
[2] => yellow
)
After this, now you can change the key => value, as you want:
$index = 0;
$myarray[$index] = "purple";
print_r($myarray);
//this will now output:
Array
(
[0] => purple
[1] => red
[2] => yellow
)
And your job is done.
Observations:
In your question, you are using two differents arrays: $myarray and $array, you are having an error because $array[$index] is different to the first $myarray[$i] = "some color...this changes with each iteration of loop";
Use print_r($yourVariable) to show what is in the variable to debug what you are doing wrong.
PHP replace string with values from array
Can you try this,
$string ="Hello <%First Name%> <%Last Name%> welcome";
preg_match_all('~<%(.*?)%>~s',$string,$datas);
$Array = array('0' => array ('First Name' => 'John', 'Last Name' => 'Smith' ));
$Html =$string;
foreach($datas[1] as $value){
$Html =str_replace($value, $Array[0][$value], $Html);
}
echo str_replace(array("<%","%>"),'',$Html);
Using PHP, search an array by key and replace value in another array with value from matched key
You can do it as following:
foreach($array_a as $elemKey => $elemValue){
foreach($elemValue as $itemKey => $itemValue){
if(isset($array_a[$elemKey][$itemKey]['label'])){
$array_a[$elemKey][$itemKey]['label'] = $array_b[$array_a[$elemKey][$itemKey]['label']];
}
}
}
print_r($array_a);
This will return:
Array
(
[0] => Array
(
[0] => Array
(
[name] => name
[label] => Name:
)
[1] => Array
(
[name] => phone_office
[label] => Office phone:
)
)
[1] => Array
(
[0] => Array
(
[name] => website
[label] => Website:
)
[1] => Array
(
[name] => phone_fax
[label] => Fax number:
)
)
)
PHP - Replace values in an array
Use an array. In the index you write the english name, the value the french name.
$arrayAux = [
'red' => 'rouge',
'black' => 'noir',
];
Then, when you want the array with the french colors:
$frenshColors = array();
foreach ($englishColors as $color) {
if (array_key_exists($color, $arrayAux)) {
$frenshColors[] = $arrayAux[$color];
} else {
$frenshColors[] = $color;
}
}
Replacing values in an array basing on values from another
You can use array_column
to make the userId
as the key and worth
as the value.
Use map
to reiterate the first array. Check if the key exist, if exist replace the value
.
$arr1 = [{"id":1,"value":40},{"id":2,"value":30}];
$arr2 = [{"userId":1,"worth":20},{"userId":2,"worth":10}];
//Use array_column to make the userId as the key and worth as the value.
$arr2 = array_column($arr2, 'worth', 'userId');
//Use `map` to reiterate the first array. Check if the key exist on $arr2, if exist replace the `value`. If not replace it with empty string.
$results = array_map( function($v) use ( $arr2 ) {
$valueInArr2 = array_search($v->id, array_column($arr2, 'userId'));
$v->value = $valueInArr2 ? $valueInArr2 : "";
return $v;
}, $arr1);
echo "<pre>";
print_r( $results);
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[id] => 1
[value] => 20
)
[1] => Array
(
[id] => 2
[value] => 10
)
)
Update: Using Object. I have not tested this.
$arr1 = .....;
$arr2 = .....;
//Make the object into array
$arr2 = array_reduce($arr2, function($c,$v) {
$c[ $v->userId ] = array(
'worth' => $v->worth;
'userId' => $v->userId;
);
return $c;
},array());
//Update the first array
$results = array_map( function( $v ) use ( $arr2 ) {
$val = array( 'id' => $v->id );
$val['value'] = isset( $arr2[ $v->id ] ) ? $arr2[ $v->id ] : "";
return $v;
}, $arr1);
find key and replace value in php array / how to
A simple loop would work, but actually it is not even required:
<?php
$data = [
[ 'app_setting_key' => "dh_company_name", '[app_setting_value' => "ABCsss" ],
[ 'app_setting_key' => "dh_address_one", 'app_setting_value' => "123 A big streetsss" ],
[ 'app_setting_key' => "dh_address_two", 'app_setting_value' => "a big city" ],
[ 'app_setting_key' => "dh_address_country", 'app_setting_value' => "JP" ],
[ 'app_setting_key' => "dh_email", 'app_setting_value' => "example@example.com" ],
[ 'app_setting_key' => "dh_phone_country", 'app_setting_value' => "JP" ],
[ 'app_setting_key' => "dh_phone_number", 'app_setting_value' => "80-3245-6000" ]
];
$key = array_search("dh_phone_number", array_column($data, 'app_setting_key'));
$data[$key]['app_setting_value'] = "+81-80-5555-5555";
var_dump($data);
The output obviously is:
array(7) {
[0]=>
array(2) {
["app_setting_key"]=>
string(15) "dh_company_name"
["[app_setting_value"]=>
string(6) "ABCsss"
}
[1]=>
array(2) {
["app_setting_key"]=>
string(14) "dh_address_one"
["app_setting_value"]=>
string(19) "123 A big streetsss"
}
[2]=>
array(2) {
["app_setting_key"]=>
string(14) "dh_address_two"
["app_setting_value"]=>
string(10) "a big city"
}
[3]=>
array(2) {
["app_setting_key"]=>
string(18) "dh_address_country"
["app_setting_value"]=>
string(2) "JP"
}
[4]=>
array(2) {
["app_setting_key"]=>
string(8) "dh_email"
["app_setting_value"]=>
string(19) "example@example.com"
}
[5]=>
array(2) {
["app_setting_key"]=>
string(16) "dh_phone_country"
["app_setting_value"]=>
string(2) "JP"
}
[6]=>
array(2) {
["app_setting_key"]=>
string(15) "dh_phone_number"
["app_setting_value"]=>
string(16) "+81-80-5555-5555"
}
}
Related Topics
How to Get Random Image from Directory Using PHP
How to Add Commas to Numbers in PHP
Simplexml_Load_String() Fail to Parse Error
Get Key of Multidimensional Array
HTML 5 Multi File Upload with PHP
Sort Array of Objects by Date Field
How to Cause a Redirect to Occur Before PHP Script Finishes
PHP & Hash/Fragment Portion of Url
Htmlpurifier Iframe Vimeo and Youtube Video
Generate Download File Link in PHP
Set Character Set Using MySQLi
How to Escape String from PHP for JavaScript
Php: Trying to Create a New Line with "\N"
How to Protect HTML Form from Spammers