Why my if-statement not checking each array inside foreach ? If someone already choose same kind of value, I want to disable it from select2 value, here's my code looks like :
function get_status_cab()
{
$status=$_POST['search'];
echo '<label for="username" class="col-sm-3 control-label">Status</label>';
echo '<div class="col-sm-9">';
echo '<select class="form-control select2" name="status">';
$cek=$this->db_umum->select("SELECT id,status FROM lembaga where id='$status'");
foreach($cek as $cek){
$statusnya = $cek->status;
}
$hasil=array(
"pusat" => "Pusat",
"cabang" => "Cabang",
"unit" => "Unit",
"proyek" => "Proyek",
"subproyek" => "Subproyek"
);
foreach($hasil as $value => $label)
{
$no=0;
if($value = $statusnya){
$disable[] = "disabled='disabled'";
}else{
$disable[] = "";
}
echo "<option value='".$value."' $disable[$no]>".$label."</option>";
$no++;
}
echo '</select></div><br/>';
}
The result is if $value = $statusnya , my whole select2 will disabled. But, It is not what I want. I want only value which is exact with $statusnya is disabled and the other is available. Any advice ?
You are using single equal(=) thats not correct you should use == for compare.
Replace this line
if($value = $statusnya){
with
if($value == $statusnya){
also define $no outside of foreach
Example:-
$no=0;
foreach($hasil as $value => $label)
{
if($value == $statusnya){
$disable[] = "disabled='disabled'";
}else{
$disable[] = "";
}
echo "<option value='".$value."' $disable[$no]>".$label."</option>";
$no++;
}
$disable = arrary();
foreach($hasil as $value => $label)
{
$no=0;
if($value = $statusnya){
$disable[$no] = "disabled='disabled'";
}else{
$disable[] = "";
}
echo "<option value='".$value."' $disable[$no]>".$label."</option>";
$no++;
}
$disable = array();
foreach($hasil as $value => $label)
{
$no=0;
if($value == $statusnya){
$disable[$no] = "disabled='disabled'";
}else{
$disable[] = "";
}
echo "<option value='".$value."' $disable[$no]>".$label."</option>";
$no++;
}
I know you already accepted an answer, and that this isn't codereview.stackexchange.com but I hope you will consider the information below.
Use the equality operator (I.e. ==
) instead of the assignment operator (I.e. =
) to check if $value is equal to $statusnya. Also you don't need to use an array to store the disabled attribute (unless you need to retain information about each option being disabled later).
foreach($hasil as $value => $label)
{
$disabled = ''; // empty string -> not disabled
if($value == $statusnya){
$disabled = "disabled='disabled'";
}
echo "<option value='".$value."' $disabled>".$label."</option>";
}
The array storage requires more memory on the server compared to the string so as your page/application grows it would require more resources. Take a look at this phpfiddle and see How big are arrays?.