Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can shorthand method applied in foreach?

So I found this SHORTHAND PHP methods on google like:

if(isset($a))
{
    $a = TRUE;
}
else
{
    $a = FALSE;
}

can be converted on a single line statement as: $a = isset($a) ? TRUE : FALSE;

which is working correctly and I have a script which I fail to apply the SHORT HAND method.

PHP:

<?php
$letters = ['1' => 'A', '2' => 'B', '3' => 'C'];

$data['LETTER'] = "";

foreach($letters as $id => $letter)
{
    $data['LETTER'] .= "<option value=$id>".$letter."</option>";
}

$html = file_get_contents('test.html');

echo $html = str_replace(array_keys($data),array_values($data),$html);
?>

I've end using with this SHORTHAND METHOD which won't work at all

$data['LETTER'] = foreach($letters as $id => $letter) ? "<option value=$id>".$letter."</option>" : "";

is there any possibilities to shorten the script above?

like image 207
Darline Avatar asked Oct 03 '22 09:10

Darline


1 Answers

There is no shorthand method for foreach, however you can achieve it with array_map:

$data['LETTER'] = implode(array_map(function($id, $letter){ return "<option value=$id>".$letter."</option>"; }, $letters));
like image 94
hsz Avatar answered Oct 07 '22 17:10

hsz