如何填充数组中的字符串?

时间:2015-11-06 19:21:49

标签: php arrays fill isset

我正在尝试在一个空''的数组值中填入一个字符串 我是否需要先使用isset或empty来检查它?

这是我的代码

echo table();

function table() {
    $a = array  ('0' => array('Jan de Boer', '213','440'),
                 '1' => array('Gerda Severin','214','442'),
                 '2' => array('Jean Dubois','215',''),
                 '3' => array('Peter Geringh','221','449'),
                 '4' => array('ricardo','666','666'));

    echo "<table border='6px'>
    <tr><th colspan='3'>Alle werknemers</th></tr>
    <tr><th>Naam</th>
    <th>kamer</th>
    <th >Toestelnummer</th></tr>";

    for ($x=0;$x<5;$x++){
        echo "<tr>";
        for($y=0;$y<3;$y++){
            echo "<td>",$a[$x][$y].'</td>';
        }
        echo "</tr>";
    }
    echo "</table>";
}

它需要填充空白'',就像字符串未知一样。

2 个答案:

答案 0 :(得分:1)

检查字符串是否为空并替换为值,在我的示例中&#39; UNKNOWN&#39;

    echo table();
function table()

{    
$a = array  ('0' => array('Jan de Boer', '213','440'),
             '1' => array('Gerda Severin','214','442'),
             '2' => array('Jean Dubois','215',''),
             '3' => array('Peter Geringh','221','449'),
             '4' => array('ricardo','666','666'));

echo "<table border='6px'>
<tr><th colspan='3'>Alle werknemers</th></tr>
<tr><th>Naam</th>
<th>kamer</th>
<th >Toestelnummer</th></tr>";

    for ($x=0;$x<5;$x++){
    echo "<tr>";
    for($y=0;$y<3;$y++){
    if($a[$x][$y] == "") $a[$x][$y] = 'UNKNOWN';
        echo "<td>",$a[$x][$y].'</td>';
    }
    echo "</tr>";
}

echo "</table>";

}

答案 1 :(得分:0)

这取决于您要检查的内容。如果字符串已设置且其中没有字符,empty将返回true,而!isset仅在字符串根本不存在时才返回true。

如果您只是想避免错误,并且可以使用''字符串,请使用!isset。如果您希望确保字符串中确实包含任何内容,请使用empty