嗨我尝试打印使用数组匹配字符串.. 问题是......它只打印 BTC打印 如果可能的话,还建议使用数组参数匹配的方法
Output Needed:
BTC print
ETH print
DOGE print
WAVES print
代码:
<?php
$coins = array("BTC", "ETH", "DOGE", "WAVES");
foreach ($coins as $coin) {
$string = 'BTC';
if (strpos($string, $coin) !== FALSE) {
echo "BTC print";
return true;
}
$string1 = 'ETH';
if (strpos($string1, $coin) !== FALSE) {
echo "ETH print";
return true;
}
$string2 = 'DOGE';
if (strpos($string2, $coin) !== FALSE) {
echo "DOGE print";
return true;
}
$string3 = 'WAVES';
if (strpos($string3, $coin) !== FALSE) {
echo "WAVES print";
return true;
}
}
echo "Not found!";
return false;
答案 0 :(得分:2)
返回会破坏你的循环。试试这个:
$coins = array("BTC", "ETH", "DOGE", "WAVES");
$found = false;
foreach ($coins as $coin) {
$string = 'BTC';
if (strpos($string, $coin) !== FALSE) {
echo "BTC print";
$found = true;
}
$string1 = 'ETH';
if (strpos($string1, $coin) !== FALSE) {
echo "ETH print";
$found = true;
}
$string2 = 'DOGE';
if (strpos($string2, $coin) !== FALSE) {
echo "DOGE print";
$found = true;
}
$string3 = 'WAVES';
if (strpos($string3, $coin) !== FALSE) {
echo "WAVES print";
$found = true;
}
}
if (!$found) {
echo "Not found!";
}
如果你在一个函数中,那么你可以添加:
return $found ;
答案 1 :(得分:0)
如果您的打印行仅在硬币名称上有所不同,您可以使用简单的循环:
$coins = ['BTC', 'ETH', 'DOGE', 'WAVES'];
foreach ($coins as $coin) {
echo "$coin print", PHP_EOL;
}
这是the demo。