0
array_map(function ($id) use ($filename) {
                $keyword = Keyword::find($id)->name;
                $filename .= $keyword . '-';
                Log::info($filename);
            }, $input['keyword_id']);

I want to add the name of keywords to my filename string variable but the values I see in the log is like :

keyword1
keyword2

The output I want is one string as a line.

keyword1keyword2 

But as you see, everytime it changes the string instead of appending.

3 Answers 3

2

You want to pass the filename as a reference, I think it will work then:

use(&$filename)

If you don't, it wont change the $filename outside of the function.

Edit: To propose a different approach for what I think you're trying to do:

foreach ($input['keyword_id'] as $index => $id) {
    $filename .= Keyword::find($id)->name;
    // dont append a "-" if this is the last keyword to be added
    if ($index < sizeof($input['keyword_id'])-1)
        $filename .= '-';
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are not returning each item inside the callback.

Just add:

return $filename

Inside the array_map callback

1 Comment

You are correct, but I think he actually isn't interested in the array returned by array_map(), he just wants to iterate over $input['keywordid'] and append these keywords names (looked up by Keyword::find()) to $filename - a simple foreach would have done the same trick, with less code, then.
0

array_map simply maps an array to another array with the same number of elements. So you need to return something in the function. The returned array can be imploded (concatenated) to get the all the keywords together.

$filename = 'myfile.txt';
$keyword_ids = [1,2];
$keywords = array_map(function ($id)  {
                return Keyword::find($id)->name;
            }, $keyword_ids);


$filename = implode('',$keywords) . '-' . $filename;
Log::info($filename);

print( $filename);
//OUTPUTS keyword1keyword2-myfile.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.