Little PHP Tricks

Casting Arrays to Objects

$jenis = array('avocado', 'rambutan', 'pisang');
$warna = array('hijau', 'merah', 'kuning');
$buah = array_combine($jenis, $warna);
$buah = (object) $buah;
var_dump($buah);

Output:

object(stdClass)[1]
public 'avocado' = string 'hijau' (length=5)
public 'rambutan' = string 'merah' (length=5)
public 'pisang' = string 'kuning' (length=6)

Delete an item from an array

unset($array[$i]);

This will break a “for ($i=0; $i

Select a random item from an associative list

$jenis = array('avocado', 'rambutan', 'pisang');
$warna = array('hijau', 'merah', 'kuning');
$buah = array_combine($jenis, $warna);
$keys = array_keys($buah);
$buah = (object) $buah;
$random = $buah->$keys[rand()%count($keys)];
echo $random;

Deal with complex structures

$pentadbir['kira'][$jumlah['pegawai']] = $val['Hasil'];

Casting the array to an object allows us to use object notation (->) and makes the code more readable:

$jumlah= (object) $jumlah;
$pentadbir = (object) $pentadbir;
$pentadbir->kira[$jumlah->pegawai] = $jumlah->Hasil;

Related Posts: