将字符串作为索引的回声数组(无串联)

时间:2018-08-11 15:21:19

标签: php

下面的代码可以正常工作。它输出:hello world

$sample_variable = "world";
echo "hello $sample_variable";

现在,我正在尝试实现相同的逻辑,但是这次使用的数组的索引是字符串。下面的代码是我想出的。这会导致错误,并且无法打印出预期的输出。 (预期输出:乳清产品的售价为3000)

$product = array(
"product_name" => "Whey", 
"product_price" => 3000
);

echo "The product $product['product_name'] is for sale for $product['product_price']";

我的问题:如何在不使用PHP串联运算符('。')的情况下回显带有字符串作为索引的数组

2 个答案:

答案 0 :(得分:1)

用法如下

<?php

$product = array(
"product_name" => "Whey", 
"product_price" => 3000
);

echo "The product $product[product_name] is for sale for $product[product_price]";

答案 1 :(得分:1)

有许多方法可以实现没有串联运算符

$product=array(
                "product_name"=>"whey",
                "product_price"=>3000

使用双引号可以做到:

echo "The product $product[product_name] is for sale for $product[product_price]";
echo "The product ${product["product_name"]} is for sale for ${product["product_price"]}";

带有预格式化的字符串:

printf("The product %s is for sale for %s ",$product['product_name'],$product['product_price']);
echo sprintf("The product %s is for sale for %s ",$product['product_name'],$product['product_price']);

当您的数组包含大量数据时,只需编写字符串并用...来解压缩数组即可。

printf("The product %s is for sale for %s ",...array_values($product));//php >=5.6
echo sprintf("The product %s is for sale for %s ",...array_values($product));//php >=5.6

输出为:

The product whey is for sale for 3000
相关问题