原生PHP(不定期更新)

1.检测一个数是不是 2 的 n 次方

<?php
/**
 * 检测一个数是不是 2 的 n 次方
 * @param int $number    数字
 * @return bool
 */
function checkSquare(int $number = 0)
{
    return (($number & $number - 1) == 0);
}

2.根据身份证号计算年龄

/**
 * 根据身份证号计算年龄
 * @param $idcard
 * @return bool|int|mixed
 */
function idcard_get_age($idcard)
{
    $retage = 0;
    if (!empty($idcard)) {
        $birthstamp = strtotime(substr($idcard, 6, 8));
        if ($birthstamp) {
            $retage = get_age($birthstamp);
        }
    }
    return $retage;
}
/**
 * 根据生日$time_birthday及指定时间$time_current,计算年龄
 * @param $time_birthday
 * @param string $time_current
 * @return bool|int|mixed
 */
function get_age($time_birthday, $time_current = '')
{
    $result = false;
    if (empty($time_current)) {
        $time_current = time();
    } else {
        is_numeric($time_current) or $time_current = strtotime($time_current);
    }

    is_numeric($time_birthday) or $time_birthday = strtotime($time_birthday);

    if (!$time_current || !$time_birthday || $time_current < $time_birthday) {
        $result = false;
    } else {
        $date_birthday = array('Y' => date('Y', $time_birthday), 'md' => date('md', $time_birthday));
        $date_current = array('Y' => date('Y', $time_current), 'md' => date('md', $time_current));
        $age = $date_current['Y'] - $date_birthday['Y'] - (($date_current['md'] < $date_birthday['md']) ? 1 : 0);
        $result = $age;
    }

    return $result;
}

3.ip 转数字

<?php
// 移位运算 ip 转数字
function ipToInt($ip = ''){
    $ipArr = explode('.', $ip);
    return (intval($ipArr[0]<<24))|(intval($ipArr[1]<<16))|(intval($ipArr[2]<<8))|(intval($ipArr[3]));
}
echo ipToInt('*.*.*.*');

# 数字转 ip echo long2ip($int);
# 系统自带函数 ip2long($ip),遇到 '47.106.082.170' 会返回 false (PHP7环境)

4. 字符串($str)成整数

1. 强制类型转换:(integer)$str
2. 直接转换:settype($str, integer)
3. intval($str)

5. 统计字符串($str)长度

1. strlen($str)     // 统计英文字符串长度
2. mb_strlen($str)  // 统计中文字符串长度

6. 获取昨天的时间

<?php
# 只能准确的获取日期,但是时间会慢6个小时
echo date('Y-m-d', strtotime('-1 day'));

# 准确的获取日期以及时间
echo date('Y-m-d H:i:s', time()-60*60*18);
?>

7. 获取上个月第一天以及最后一天

<?php
# 上月第一天
echo date('Y-m-01', strtotime('-1 month'));

# 上月最后一天
echo date('Y-m-t', strtotime('-1 month'));

8. PHP7 round()函数精度

php7下 round()函数精度有问题,可以在php脚本中添加如下代码

ini_set('serialize_precision', -1);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值