php - 在 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
会不必要地麻烦,应该有一个更优雅的方法。
解决方案
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"
推荐阅读
- python - 过时的元素参考:元素未使用 chrome Web 驱动程序附加到页面文档
- python - GCS:当我尝试使用 POSTMAN 向签名 URL 发出 PUT 请求时出现 SignatureDoesNotMatch 错误
- ios - Swift:numberOfRowsInSection 和 cellForRowAt 未被调用
- javascript - Hash Table - 为什么我们对键进行散列而不是仅使用输入作为键?
- stm32 - 无法使用 HAL 驱动程序在 STM32F429 上写入双字
- python - Stackplot 使用一长串数据帧标题
- android - Android Cordova:使 WebView HTML 元素透明以查看原生元素
- python - 你如何处理Python中的多重嵌套单引号和双引号
- java - 如何使两个模块相互依赖
- php - 在 Laravel 中创建备份控制器