jeudi 29 juin 2017

PHP - [Best way to] Concatenate between strings with ternary or with previous "settlements"?

General question: which one of these options is the best practice and why?

Specific or narrow situation: Let's say I read a file list.txt and store the data inside an array (assume list.txt content: "Name: John" & "Product: Banner"). E.g.:

$txt='/files/list.txt';
$archive = fopen($txt,'r');
$le = fread($archive,filesize($txt));

$data = explode("\n",$le);
$person = explode(":",$data[0]);
$name = $person[1]; # "John"

$field1 = explode(":",$data[1]);
$field01 = $field1[0]; # "Product"
$field1 = $field1[1]; # "Banner"

Now, I want to send an email, for the sake of the example, I want to send with or without the information about the product. Assume predefined body/table:

    <tr>
        <td>
            <b>'.$name.'</b>
        </td>
    </tr>
'.((isset($field1) || isset($field1[0])) ?
    '<tr>
        <td>
            <b>'.$field01.':</b>'.$field1.'
        </td>
    </tr>' : '' ).
'</table>

Is it safe? Is there a better way to do this (n performance wise)? Is there a chance that I get "Undefined variable" if the variable itself is not set for not having a matching field in the list.txt? Specifically or in general concatenation.

Related: if statement in the middle of concatenation?

Aucun commentaire:

Enregistrer un commentaire