Rachmad Rachmad - 1 year ago 55
PHP Question

How can I get else value when compare key of array and value?

output my first array

$arr_val
:

Array
(
[0] => 0
[1] => 2
[2] => 3
)


output second array
$pecah_arr
:

Array
(
[0] => Kunyit dipercaya sebagai salah satu rempah yang dapat mendukung kesehatan hingga untuk pengobatan
[1] => Sayangnya, pemakaian yang keliru justru berdampak sebaliknya
[2] => Seperti berita yang diangkat NBC News, seorang wanita asal San Diego yang menerima pengobatan kunyit intravena harus mengakhiri nyawa.
[3] => Jade Erick meninggal 16 Maret lalu setelah pergi ke India untuk melakukan pengobatan rempah-rempah untuk penyakit eksim yang dideritanya.
)


I want to get output like this,
if value in
$arr_val
same with key of
$pecah_arr
, print the value that same.
but if value in
$arr_val
not same with key of
$pecah_arr
, print the value that not same.

my logic like this:

$hasil_ringkasan=array();
foreach ($arr_val as $key => $value) {
foreach ($pecah_arr as $key2 => $value2) {
if($value==$key2){
$no_doc=$value+1;
array_push($hasil_ringkasan, $value2);
//INSERT KE DB untuk Learning
$q=$this->db->query("INSERT INTO tb_sementara
VALUES('$key2[$value]','$no_doc','$fitur1_uji[$value]','$fitur2_uji[$value]',
'$fitur3_uji[$value]','$fitur4_uji[$value]','$fitur5_uji[$value]','$fitur6_uji[$value]','ringkasan')");

}else{
// INSERT KE DB untuk Learning
$q=$this->db->query("INSERT INTO tb_sementara
VALUES('$key2[$value]','$no_doc','$fitur1_uji[$value]','$fitur2_uji[$value]',
'$fitur3_uji[$value]','$fitur4_uji[$value]','$fitur5_uji[$value]','$fitur6_uji[$value]','bukan')
");
}

}
}


Although in
if
had worked, but I dont know why in
else
dont work.
thanks..

Answer Source

You do not need to iterate over $arr_val. Use in_array() instead.

$hasil_ringkasan=array();
    foreach ($pecah_arr as $key2 => $value2) {
        if(in_array($key2,$arr_val)){
            $no_doc=$value+1;
            array_push($hasil_ringkasan, $value2);
            //INSERT KE DB untuk Learning
            $q=$this->db->query("INSERT INTO tb_sementara 
            VALUES('$key2[$value]','$no_doc','$fitur1_uji[$value]','$fitur2_uji[$value]',
                '$fitur3_uji[$value]','$fitur4_uji[$value]','$fitur5_uji[$value]','$fitur6_uji[$value]','ringkasan')");

            }else{
            // INSERT KE DB untuk Learning
            $q=$this->db->query("INSERT INTO tb_sementara 
            VALUES('$key2[$value]','$no_doc','$fitur1_uji[$value]','$fitur2_uji[$value]',
                '$fitur3_uji[$value]','$fitur4_uji[$value]','$fitur5_uji[$value]','$fitur6_uji[$value]','bukan') 
            ");
        }


}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download