php - Reducing array to string avoiding foreach
Get the solution ↓↓↓Solution:
You can use array_map and implode like:
$list = [
'k1' => 'vA1 vA2 vA2',
'k2' => 'vB1 vB2 vB2',
'k3' => '',
'k4' => 'vC1 vC2 vC2',
'k5' => NULL,
'k6' => 'vD1 vD2 vD2',
];
$list = array_filter($list, function ($value) {
return $value !== null;
});
$array = array_map(function ($key, $value) {
return trim($key . ' ' . $value);
}, array_keys($list), $list);
echo implode('; ', $array);
The result is:
k1 vA1 vA2 vA2; k2 vB1 vB2 vB2; k3; k4 vC1 vC2 vC2; k6 vD1 vD2 vD2
Answer
Solution:
This's not an answer but some thoughts and data about the question and the answers.
My goal is to avoidforeach
because It's slow.
In a really surprising way, my implementation is the quickest!
As pointed out by @kunruhforeach
is quicker than collection of functions and allocating memory for intermediate values
The code under profiler:
<?php
function filterNull($v) {
if ($v === null) {
return false;
}
return true;
}
class ProfileSolution
{
const LOOP_LV1 = 200;
const LOOP_LV2 = 300;
public function reduceIvan($list){
$_buff="";
$_sep="";
foreach ($list as $k => $v){
if($v===null){
continue;
}
$_buff.="$_sep$k $v";
$_sep="; ";
}
return $_buff;
}
public function reduceMateiMihai ($list)
{
$_list = array_filter($list, function ($value) {
return $value !== null;
});
$array = array_map(function ($key, $value) {
return trim($key . ' ' . $value);
}, array_keys($_list), $_list);
return implode('; ', $array);
}
public function reduceMasterFly($list){
$array = [];
foreach( $list as $key => $value ){
$tmp = [];
if ( !is_null($value) ){
$tmp[] = $key;
$tmp[] = $value;
$array[] = implode(" ", $tmp);
}
}
return implode("; ", $array);
}
public function reduceKunruh($list) {
$result = "";
foreach ($list as $key => $value) {
if ($value === NULL) continue;
$result .= " $key $value;";
}
// remove trailing semicolon
$result = substr($result, 0, -1);
return $result;
}
public function reduceHmmm ($list)
{
$result = array();
array_walk($list, function($value, $key) use (&$result) {
if($value!==null) {
$result[] = $key .' '. $value;
}
});
return print_r(implode('; ', $result),true);
}
public function reduceAd ($list)
{
$filteredList = array_filter($list, 'filterNull');
return implode("; ", array_map(function($k, $v){
return "$k $v";
}, array_keys($filteredList), array_values($filteredList)));
}
public function testReduceIvan ($list)
{
$t=0;
while($t++ < self::LOOP_LV2){
$res="";
$res=$this->reduceIvan($list);
}
}
public function testReduceMateiMihai ($list)
{
$t=0;
while($t++ < self::LOOP_LV2){
$res="";
$res=$this->reduceMateiMihai($list);
}
}
public function testReduceMasterFly ($list)
{
$t=0;
while($t++ < self::LOOP_LV2){
$res="";
$res=$this->reduceMasterFly($list);
}
}
public function testReduceKunruh ($list)
{
$t=0;
while($t++ < self::LOOP_LV2){
$res="";
$res=$this->reduceKunruh($list);
}
}
public function testReduceHmmm ($list)
{
$t=0;
while($t++ < self::LOOP_LV2){
$res="";
$res=$this->reduceHmmm($list);
}
}
public function testReduceAD ($list)
{
$t=0;
while($t++ < self::LOOP_LV2){
$res="";
$res=$this->reduceAD($list);
}
}
public function run ()
{
$list =[
'k1' => 'magni dolores eos qui ratione voluptatem sequi nesciunt. Neque',
'k2' => 'porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem',
'k3' => '',
'k4' => 'minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem',
'k5' => NULL,
'k6' => 'non numquam eius modi tempora incidunt labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis',
'k7' => 'aut fugit, sed quia consequuntur',
'k8' => 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae',
'k9' => 'vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam',
'k10' => 'nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam',
'k11' => 'inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor',
'k12' => 'amet, consectetur, adipisci velit, sed quia',
'k13' => Null,
'k14' => 'pain, but because occasionally circumstances occur in which toil and',
'k15' => 'explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes',
'k16' => 'amet, consectetur, adipisci velit, quia',
'k17' => 'or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter',
'k18' => 'consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain',
'k19' => 'voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque',
'k20' => Null,
'k21' => 'inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit ',
'k22' => 'amet, consectetur, velit, sed quia',
'k23' => 'laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas',
'k24' => 'non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis',
];
$t=0;
while($t++ < self::LOOP_LV1){
$this->testReduceIvan($list);
$this->testReduceMateiMihai($list);
$this->testReduceMasterFly($list);
$this->testReduceKunruh($list);
$this->testReduceHmmm($list);
$this->testReduceAD($list);
}
}
}
$o = new ProfileSolution();
$o->run();
Answer
Solution:
I dont think there will be significant execution time difference with foreach or any array_* function. It will matter only if records increase more than 100K I guess.
$result = array();
array_walk($list, function($value, $key) use (&$result) {
if($value!==null) {
$result[] = $key .' '. $value;
}
});
print_r(implode('; ', $result));
Why don't you compare the time taken from all answer and choose the best one ;)
Answer
Solution:
Try this,
function reduce($list){
$array = [];
foreach( $list as $key => $value ){
$tmp = [];
if ( !is_null($value) ){
$tmp[] = $key;
$tmp[] = $value;
$array[] = implode(" ", $tmp);
}
}
return implode("; ", $array);
}
Answer
Solution:
I think this is a pretty clean, simple solution:
function reduce($list) {
$result = "";
foreach ($list as $key => $value) {
if ($value === NULL) continue;
$result .= " $key $value;";
}
// remove trailing semicolon
$result = substr($result, 0, -1);
return $result;
}
Answer
Solution:
I think you should use array_values, array_keys, array_map, array_filter and implode.
function filterNull($v) {
if ($v === null) {
return false;
}
return true;
}
$filteredList = array_filter($list, 'filterNull');
echo implode("; ", array_map(function($k, $v){
return "$k $v";
}, array_keys($filteredList), array_values($filteredList)));
array_filter will remove the empty values. array_keys will retrieve the keys. array_values will retrieve the values. array_map will process each cell. implode will glue each cell of the array together.
Edit: I've changed the whole code since I've misread the first time. Now, the solution is compliant with your needs.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: your system folder path does not appear to be set correctly. please open the following file and correct this: index.php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.