首页 > 解决方案 > 在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”时,如何定义该值?

标签: phparraysundefined

解决方案


<?php
    $input=$_POST['input'];
    if(isset($_POST['submitButton'])){
    if (str_contains('k', $input)) {
        $explodedinput=explode('k', $input);

        echo $explodedinput[0];
        echo ' ';
        echo $explodedinput[1];
    }

 
    }
?>

推荐阅读