The loop below outputs from the $defaultValues values, there are 2 nested arrays in this array which are "colors" and "lessons".
This loop also takes the substring values from the $search array and replaces them with the values from the $replace.
Question: How to replace nested array clause value "colors" and "lessons" from $defaultValues
values: "colors"=>["4", "5", "6"] and "lessons" =>["7 " , " 8", "9"] from $replace"
I can’t figure out how to do this, my current code outputs this:
Name: 1
Age: 2
Whe are u from: 3
Your favorite color: 4
Choose courses: 7
Your comment: 10
I would like the code to output this:
Name: 1
Age: 2
Whe are u from: 3
Your favorite color: 4,5,6
Choose courses: 7,8,9
Your comment: 10
$defaultValues = [
"name" => "Name: <div class='user'> write your name </div>",
"age" => "Age: <div class='age'> enter your age </div>",
"from" => "Whe are u from: <div class='from'> write where are you from </div>",
"colors" => ["Your favorite color: <div class='colors'> you didn't say your favorite color </div>"],
"lessons" => ["Choose courses: <div class='lessons'> you have not chosen any course </div>"],
"comment" => "Your comment: <div class='comment'> no comments </div>",
];
$search = [
"name" => "write your name",
"age" => "enter your age",
"from" => "write where are you from",
"colors" => ["you didn't say your favorite color"],
"lessons" => ["you have not chosen any course"],
"comment" => "no comments",
];
$replace = [
"name" => "1",
"age" => "2",
"from" => "3",
"colors" => ["4", "5", "6"],
"lessons" => ["7", "8", "9"],
"comment" => "10",
];
foreach($defaultValues as $key => $items){
echo "<div class='block'>";
if(is_array($items)){
foreach($items as $child){
$items = str_replace($search[$key], $replace[$key], $child);
}
}
echo $items = str_replace($search[$key], $replace[$key], $items);
echo "</div>";
}
3
Answers
If you meant to join the array of colors and lessons to create the string to replace the corresponding placeholders you may use the function
implode
https://www.php.net/manual/en/function.implode.php
Here’s the code fragment:
The corresponding output:
Here’s the whole snippet: https://onlinephp.io/c/098a6
You just need to use
implode
to parse the array into a comma-separated string for output!will output you looking for