Print an address based on an format in XML

I have a database table with three columns: street name, house number (nullable) and city.

I want to print the address using is format:

Correct: "Wall Street, 11 – New York"

Correct (house number null): "Wall Street – New York"

Wrong (house number null): "Wall Street, – New York"

I don’t want to use an if/else statement because I have some different formats based on the country, so I thought about XML.

Add Comment
2 Answer(s)

Because you have different formats based on the country, you should use the sprintf function, and give as the first parameter the format you want and then the rest of parameters. Example:

$format = '%1$s %2$s - %3$s'; echo sprintf($format, $house, ($number ?  ', '.$number. : ''), $city); 
Answered on July 16, 2020.
Add Comment

you can try to make it generic by having something like the following:

echo $street . ' ' . $number ? ',' . $number : '' . $city ? ' - ' . $city : '';  
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.