Reputation: 45
How can I deal with this error:
Warning:
in_array()
expects parameter 2 to be array, string given in C:\xampp\htdocs\php\index.php
My code is:
if (!isset($_GET['jenis'])) {
$jenis = "";
} else {
$jenis = $_GET['jenis'];
}
<li><input type="checkbox" onclick="jeniss();" name="jenis[]" value="11" <?php if (in_array("11",$jenis)) { echo "checked"; } ?> > <a> 11 </a> </li>
<li><input type="checkbox" onclick="jeniss();" name="jenis[]" value="12" <?php if (in_array("12",$jenis)) { echo "checked"; } ?> > <a> 12 </a> </li>
<li><input type="checkbox" onclick="jeniss();" name="jenis[]" value="13" <?php if (in_array("13",$jenis)) { echo "checked"; } ?> > <a> 13 </a> </li>
Note: the error at HTML input type when the page has not posted anything yet.
Upvotes: 1
Views: 5692
Reputation: 5514
In order to use in_array()
you have to make sure that your second parameter is an array, you are providing a string as the second parameter.
Reason for this is that when $jenis
is set by the form, it already is an array how you defined it, however before posting the form $jenis
is not set and thus it will be set an empty string on line 2.
All you have to change is change line 2 to $jenis = array();
.
Good practice is to make sure that a variable always has the same type or null. It will generally prevent these kind of mistakes (that might also become hard to test in complex cases).
Upvotes: 0
Reputation: 12391
The second parameter needs to be an array and you are passing the string instead of array.
It is like this in_array("value_you_wanna_look",$array)
$_GET['jenis']
is a string value not an array.
You may check against the value of $jenis like this
<?php if ($jenis=="11") echo "checked"; ?> // and so on for other values
OR
Enter the value in array like this:
$jenis = array($_GET['jenis']);
Upvotes: 1
Reputation: 11987
As your error says, you are trying to pass string instead of array for in_array()
. Please check this to have a better look at in_array()
According to your code
if (!isset($_GET['jenis'])) {
$jenis = array(); //<--- have empty array be default.
} else {
$jenis = (array) $_GET['jenis']; //<---- change this line. You can typecast to array if you are getting only one value.
}
Upvotes: 1
Reputation: 1759
You have to check $_GET['jenis']
is string or array by using
var_dump($_GET['jenis']);
if it is string than you have to define as a array just like that
$jenis = array($_GET['jenis']);
and you can use in_array
Upvotes: 3