PHP取随机数

    /**
 * 根据类型选择字符串
 * @param  integer $type [description]
 * @return [type]        [description]
 */
function getStr($type=1)
{
    $str = '';
    switch ($type) {
        case 1:
            # 数字
            $str = '1234567890';
            break;
        case 2:
            # 字母
            $str = 'zxcvbnmlkjhgfdsaqwertyuiopMNBVCXZASDFGHJKLPOIUYTREWQ';
            break;
        case 3:
            # 字母加数字
            $str = '0123456789mnbvcxzasdfghjklpoiuytrewqMNBVCXZLKJHGFDSAPOIUYTREWQ';
            break;
        case 4:
            # 生僻字
            $str = '赵钱孙李周吴郑王';
            break;
    }
    return $str;
}

/**
 * [getCode description]得到随机数
 * @param  integer $num  [description]
 * @param  integer $type [description]
 * @return [type]        [description]
 */
function getCode($num = 6, $type = 1)
{
    //得到字符串
    $str = getStr($type);
    //查询字符串长度
    $len = strlen($str);
    $code = '';
    for ($i = 0; $i < $num; $i++) {
        $rand = mt_rand(0,$len - 1);
        $code .= $str[$rand];
    }
    return $code;
}

echo getCode($num = 6, $type = 3);

猜你喜欢

转载自blog.csdn.net/qq_41825819/article/details/81811165