首页 > 解决方案 > 在 PHP 中确定输出格式的最有效方法

问题描述

给定三个可选变量,它们可以是数字或null,如下所示:

$length;
$width;
$height;

所需的输出将取决于有多少变量不为空:

// Only one variable:
echo '{$width}"';

// Two variables:
echo '{$width}" x {$height}"';

// All three variables:
echo '{$length}" x {$width}" x {$height}"';

如果我们不知道哪些变量有数据,哪些是空的,那么打印正确格式的最佳方法是什么?

似乎做一个多嵌套if会不必要地麻烦,应该有一个更优雅的方法。

标签: php

解决方案


A short, but maybe not the most efficient, would be to add all of the items to an array (with a default of null) and then use array_filter to remove nulls (note that it will also remove 0's, but with measurements that probably won't be a problem.)

Then implode() the result with " x as a separator. Finally add " to the end

$width = 10;
$length = 20;
$height = 5;

echo implode('" x ', array_filter([$length ?? null, $width ?? null, $height ?? null])).'"';

gives

20" x 10" x 5"

with

$width = 10;
//$length = 20;
$height = 5;

it gives

10" x 5"

推荐阅读