Home > Net >  How to add key and value in array without foreach, Laravel
How to add key and value in array without foreach, Laravel

Time:01-13

I want to make array without foreach loop. This is should be returned:

array:4 [
  0 => array:1 [
    "name" => "tag1"
  ]
  1 => array:1 [
    "name" => "tag2"
  ]
  2 => array:1 [
    "name" => "tag3"
  ]
  3 => array:1 [
    "name" => "tag4"
  ]
]

I made it to work like this:

            $tags=[];
            $j=0;
            foreach($woo->tags as $tag){
                $tags[$j]['name']=$tag;
                $j  ;
            }

But when I have a lot of tags it can be slow in foreach loop. My tags are saved in database in text field like tag1,tag2,tag3,tag4 enter image description here

Is there any other faster way to return this..

CodePudding user response:

Try array_map, I haven't actually benchmarked the both but it is one of (if not your only) alternative:

$tags = array_map(function($tag) {
    return ['name' => $tag];
}, $woo->tags);

For what it's worth, if you are actually storing so many tags in a singular column that it actually slows PHP down, might be something you need to step back and think about improving.

  • Related