在 php 中定义未定义的数组键
Define undefined array key in php
我正在使用以下网站在一个字段中插入两个由字母“k”分隔的代码。
<?php
if(isset($_POST['submitButton'])){
$input=$_POST['input'];
$explodedinput=explode('k', $input);
echo $explodedinput[0];
echo ' ';
echo $explodedinput[1];
}
?>
<form id="login" method="post">
<input type="password" name="input">
<input type="submit" name="submitButton" value="SEND">
</form>
问题出自用户错误,错误引入了不带“k”的代码。然后,出现代码 Warning: Undefined array key 1.
当输入中不存在“k”时,如何定义该值??
<?php
$input=$_POST['input'];
if(isset($_POST['submitButton'])){
if (str_contains('k', $input)) {
$explodedinput=explode('k', $input);
echo $explodedinput[0];
echo ' ';
echo $explodedinput[1];
}
}
?>
对于 PHP 7 及以下使用 strpos
or stripos
。我创建了一个这样的函数
function itContains($myString, $search, $caseSensitive = false) {
return $caseSensitive ?
(strpos($myString, $search) === FALSE ? FALSE : TRUE):
(stripos($myString, $search) === FALSE ? FALSE : TRUE);
}
所以你可以像这样使用它
if(isset($_POST['submitButton'])){
$input=$_POST['input'];
if (itContains($input, 'k')) {
$explodedinput=explode('k', $input);
echo $explodedinput[0]." ".$explodedinput[1];
}
}
对于PHP8+
if (str_contains('How are you', 'are')) {
echo 'yes it contains';
}
如果要使用零和一进行索引,可以检查分解的零件数 returns 是否大于 1。
您只是在检查是否设置了 submitButton
,但您还可以在输入爆炸时检查是否设置了 input
。
if (isset($_POST['submitButton']) && isset($_POST['input'])) {
$explodedinput = explode('k', $_POST['input']);
if (count($explodedinput) > 1) {
echo $explodedinput[0];
echo ' ';
echo $explodedinput[1];
}
}
我正在使用以下网站在一个字段中插入两个由字母“k”分隔的代码。
<?php
if(isset($_POST['submitButton'])){
$input=$_POST['input'];
$explodedinput=explode('k', $input);
echo $explodedinput[0];
echo ' ';
echo $explodedinput[1];
}
?>
<form id="login" method="post">
<input type="password" name="input">
<input type="submit" name="submitButton" value="SEND">
</form>
问题出自用户错误,错误引入了不带“k”的代码。然后,出现代码 Warning: Undefined array key 1.
当输入中不存在“k”时,如何定义该值??
<?php
$input=$_POST['input'];
if(isset($_POST['submitButton'])){
if (str_contains('k', $input)) {
$explodedinput=explode('k', $input);
echo $explodedinput[0];
echo ' ';
echo $explodedinput[1];
}
}
?>
对于 PHP 7 及以下使用 strpos
or stripos
。我创建了一个这样的函数
function itContains($myString, $search, $caseSensitive = false) {
return $caseSensitive ?
(strpos($myString, $search) === FALSE ? FALSE : TRUE):
(stripos($myString, $search) === FALSE ? FALSE : TRUE);
}
所以你可以像这样使用它
if(isset($_POST['submitButton'])){
$input=$_POST['input'];
if (itContains($input, 'k')) {
$explodedinput=explode('k', $input);
echo $explodedinput[0]." ".$explodedinput[1];
}
}
对于PHP8+
if (str_contains('How are you', 'are')) {
echo 'yes it contains';
}
如果要使用零和一进行索引,可以检查分解的零件数 returns 是否大于 1。
您只是在检查是否设置了 submitButton
,但您还可以在输入爆炸时检查是否设置了 input
。
if (isset($_POST['submitButton']) && isset($_POST['input'])) {
$explodedinput = explode('k', $_POST['input']);
if (count($explodedinput) > 1) {
echo $explodedinput[0];
echo ' ';
echo $explodedinput[1];
}
}