Autor Zpráva
Petr1979
Profil *
Zdravím,

řeším si nějakou drobnou fci a mám tu zádrhel:
function Generate($type = 'all') {
        $man = array('Jiří', 'Jan');
        $woman = array('Marie', 'Jana');
        $all = array_merge($man, $woman);
        $tmp = $$type;
        return $tmp[rand(0, count($$type) - 1)];
    }

Konkrétně problém je zde: (bez použití proměnné $tmp to nefunguje a chci si ušetřit ten jeden zbytečný řádek)
     function Generate($type = 'all') {
        $man = array('Jiří', 'Jan');
        $woman = array('Marie', 'Jana');
        $all = array_merge($man, $woman);
//        $tmp = $$type;
        return $$type[rand(0, count($$type) - 1)];
    }

Nějaká rada? :)

Chybová hláška:
Notice: Uninitialized string offset:
juriad
Profil
Petr1979:
Na proměnné proměnné zapomeň. Je to prasárna, která jen ničí kóď.

<?php

function Generate($type = 'all') {
        $types = [];
        $types['man'] = array('Jiří', 'Jan');
        $types['woman'] = array('Marie', 'Jana');
        $types['all'] = array_merge($types['man'], $types['woman']);

        if(! isset($types[$type])) {
                return FALSE;
        } else {
                # místo tohoto lze použít i funkci array_rand
                return $types[$type][rand(0, count($types[$type]) - 1)];
        }
}

echo Generate('dog');

Vaše odpověď

Mohlo by se hodit


Prosím používejte diakritiku a interpunkci.

Ochrana proti spamu. Napište prosím číslo dvě-sta čtyřicet-sedm:

0