<?php
$array = array();
$array['{name}'] = "Agustian Romy Ariansyah";
$array['{detail.country}'] = "Indonesia";
$array['{detail.age}'] = "32";
print_r($array);
/*
Array
(
[{name}] => Agustian Romy Ariansyah
[{detail.country}] => Indonesia
[{detail.age}] => 32
)
*/
echo $array['{name}']; //Agustian Romy Ariansyah
echo count($array); //3
echo implode(array_keys($array)); //{name}{detail.country}{detail.age}
?>
Minggu, 13 Februari 2022
PHP Create Array Value With Key
PHP String Replace All From Array
<?php
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
$array = array(
'{name}' => 'Agustian Romy Ariansyah',
'{detail.country}' => 'Indonesia',
'{detail.age}' => '32'
);
$result = str_replace(array_keys($array), array_values($array), $string);
echo $string; //My name is Agustian Romy Ariansyah. I live in Indonesia and age is 32
?>
<?php
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
$array = array(
'name' => 'Agustian Romy Ariansyah',
'detail' => array(
'country' => 'Indonesia',
'age' => '32'
)
);
foreach($array as $key => $value) {
if(is_array($value)) {
foreach($value as $key2 => $value2) {
$string = str_replace("{".$key.".".$key2."}", $value2, $string);
}
} else {
$string = str_replace("{".$key."}", $value, $string);
}
}
echo $string; //My name is Agustian Romy Ariansyah. I live in Indonesia and age is 32
?>