I’m using the following web to insert two codes separated by the letter “k” in just one field.
<?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>
The problem comes with the user is wrong and introduces a code without “k” by mistake. Then, it appears the code Warning: Undefined array key 1.
How can I define that value when “k” is not present in the input??
Advertisement
Answer
For PHP 7 and below use strpos
or stripos
. I created a function like this
function itContains($myString, $search, $caseSensitive = false) { return $caseSensitive ? (strpos($myString, $search) === FALSE ? FALSE : TRUE): (stripos($myString, $search) === FALSE ? FALSE : TRUE); }
so you may use it like
if(isset($_POST['submitButton'])){ $input=$_POST['input']; if (itContains($input, 'k')) { $explodedinput=explode('k', $input); echo $explodedinput[0]." ".$explodedinput[1]; } }
For PHP 8+
if (str_contains('How are you', 'are')) { echo 'yes it contains'; }