php经常遇到的方法和问题整理

1、array_shift() 函数

定义和用法
array_shift() 函数用于删除数组中的第一个元素,并返回被删除的元素。

注释:如果键名是数字的,所有元素都将获得新的键名,从 0 开始,并以 1 递增(参见下面实例)。


<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a);
print_r ($a);
?>

//运行的结果
red
Array ( [b] => green [c] => blue )

2、??号的问题


$prarams['username'] = '';
$username = $prarams['username'] ?? '张三';
echo $username;

//输出为空

3、array_flip() 函数

反转数组中的键名和对应关联的键值:


<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>

//结果是
Array ( [red] => a [green] => b [blue] => c [yellow] => d )

4. number_format()保留两位小数点

<?php
$num = 3.14159; // 要进行格式化的数字
$formattedNum = number_format($num, 2); // 设置保留两位小数
echo $formattedNum; // 输出结果:3.14
?>

5.parse_str() 函数把查询字符串解析到变量中

注释:php.ini 文件中的 magic_quotes_gpc 设置影响该函数的输出。如果已启用,那么在 parse_str() 解析之前,变量会被 addslashes() 转换。

把查询字符串解析到变量中:

<?php
parse_str("name=Peter&age=43");
echo $name."<br>";
echo $age;
?>

在这里插入图片描述

存储变量到一个数组中:

<?php
parse_str("name=Peter&age=43",$myArray);
print_r($myArray);
?>

在这里插入图片描述

6.call_user_func() 利用回调函数处理字符串 call_user_func_array是利用回调函数处理数组

// 1、 调用自定义函数
function test($a, $b)
{
    echo $a + $b;
}
// 字符串传参
call_user_func('test', 1, 2); // 3
// 数组式传参
call_user_func_array('test', [1, 2]); // 3

// 2、 调用匿名函数
call_user_func(function($a, $b){ echo $a + $b ;}, 1, 2); // 3
call_user_func_array(function($a, $b){ echo $a + $b ;}, [1, 2]); // 3

// 3、 调用系统函数
echo call_user_func('strtoupper', 'abc'); // ABC
echo call_user_func_array('strtoupper', ['abc']); // ABC

// 4、 调用类中的函数
class Test
{
    static public function demo($a, $b)
    {
        echo $a + $b;
    }
    public function show($a, $b)
    {
        echo $a + $b;
    }
}
// 调用类中的静态方法
   // 类名方法名以数据形式
call_user_func(['Test', 'demo'], 1, 2); // 3
call_user_func_array(['Test', 'demo'], [1, 2]); // 3
   // 类名方法名以字符串形式
call_user_func('Test::demo', 1, 2); // 3
call_user_func_array('Test::demo', [1, 2]); // 3

// 调用类中的动态方法,对象和方法必须通过数组形式传递
call_user_func([new Test, 'show'], 1, 2); // 3
call_user_func_array([new Test, 'show'], [1, 2]); // 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值