PHP 常用函数

目录

检测数组是否存在某值:

合并多个数组

递归数组键值对,把键值当作输入参数给指定函数

设置响应头

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

检测字符串编码

字符串按from_encoding解码按to_encoding转码

关联数组键大小写改变

在数组的头部添加或删除

使用call_user_func_array调用各种环境函数

ini_set在PHP语言里设置的php.ini文件中


检测数组是否存在某值:

bool in_array(
    mixed $needle, 
    array $haystack, 
    [ bool $strict = FALSE ]
)
参数描述
needle必需。规定要在数组搜索的值。如果是字符串,则比较是区分大小写的。
haystack必需。规定要搜索的数组。不管是索引数组还是关联数组,只搜索值值
strict可选。如果设置该参数为真,则in_array()函数还会检查针的类型是否和草堆中的相同

合并多个数组

// 后面的数组 会按"key是否重复"重写前面数组参数key-value对
array array_merge (
    array $array1,
    [ array $array2 = null, 
    array $_ = null, ]
)
// 注意,此函数的结果只会输出一个重新从零开始索引的索引数组


$age=array(2 =>"35", '6'=>"37",4=>"43");
var_dump(array_merge($age));
/* retult:
    Array
    (
        [0] => 35
        [1] => 37
        [2] => 43
    )
*/
参数描述
array1必需。规定数组。
array2可选。规定数组。
_可选。规定数组。

递归数组键值对,把键值当作输入参数给指定函数

bool array_walk_recursive (
    array &$input, 
    callback $funcname, 
    [ mixed $userdata = null, ]
)


function myfunction($value,$key)
{
    echo "The key $key has the value $value".PHP_EOL;
}
$a1=array("a"=>"red","b"=>"green");
$a2=array($a1,"1"=>"blue","2"=>"yellow");
// 比array_walk多了递归,也就是说array_walk_recursive会把多维数组递归成一维数组
array_walk_recursive($a2,"myfunction");
/* result:
    The key a has the value red
    The key b has the value green
    The key 1 has the value blue
    The key 2 has the value yellow
 */

// 若是array_walk
array_walk($a2,"myfunction");
/*
    Notice: Array to string conversion in D:\wamp64\apps\Blog\test.php on line 4
    The key 0 has the value Array
    The key 1 has the value blue
    The key 2 has the value yellow
*/
参数描述
&$input必需。规定数组。
funcname必需。用户自定义函数的名称。
userdata可选。规定用户自定义函数的参数,您可以为函数设置一个或多个参数。

设置响应头

void header (
    string $string, 
    [ bool $replace = true, $http_response_code = null ]
)
参数描述
string必需请求头字符串,例如:标题(“位置:HTTP://www.example.com/”)
replace可选。相同的头信息不并存,会被替换
http_response_code可选。强制指定HTTP响应的值。注意,这个参数只有在报文字符串(string)不为空的情况下才有效。

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

void parse_str (
    string $str,
    [ array &$arr = null, ]
)
参数描述
str必需。规定要解析的字符串。
&$arr可选。规定存储变量的数组名称。该参数指示变量存储到数组中。

检测字符串编码

string|false mb_detect_encoding (
    string $str,
    [ string|string[] $encoding_list = null, bool $strict = false] 
)

字符串按from_encoding解码按to_encoding转码

string mb_convert_encoding (
    string|array $str,
    string $to_encoding,
    [ string|string[] $from_encoding = null ])

关联数组键大小写改变

array array_change_key_case(
    array $input, 
    [int $case = null, ]
)
input必需。规定要使用的数组。
case可选可能的值:
  • CASE_LOWER(0,false) - 默认值。将数组的键转换为小写字母。
  • CASE_UPPER(1,true) - 将数组的键转换为大写字母。

在数组的头部添加或删除

mixed array_shift ( array &$array ) //将数组开头的单元移出数组,会破坏数字索引
int array_unshift ( array &$array , mixed $var [, mixed $_... ] )  //在数组开头插入一个或多个单元,所有的数值键名将修改为从零开始重新计数,所有的文字键名保持不变。 

<?php
$a = [4=>1,5=>2];
array_shift($a);
print_r($a);

$queue = array('0'=>"orange", 'a'=>"banana");
array_unshift($queue, [4=>"apple"], "raspberry");
print_r($queue);

/* result:
    Array
    (
        [0] => 2
    )
Array
    (
        [0] => Array
        (
            [4] => apple
        )
    
        [1] => raspberry
        [2] => orange
        [a] => banana
    )
*/

使用call_user_func_array调用各种环境函数

mixed call_user_func_array ( callback $callback , array $param_arr )

// 调用普通函数foobar('one', 'two')
call_user_func_array("foobar", array("one", "two"));
$foo = new Foo();
// 调用Foo类的实例函数bar('three', 'four')
call_user_func_array(array($foo, "bar"), array("three", "four"));
// 调用__NAMESPACE__空间的Foo类的类函数test('Hannes')
call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'))

ini_set在PHP语言里设置的php.ini文件中

// ini_set用来设置php.ini的值,在函数执行的时候生效,脚本结束后,设置失效。无需打开php.ini文件,就能修改配置
string ini_set(string $varname, string $newvalue) 
/* 常见设置:
    @ini_set('memory_limit', '64M'); 
    'menory_limit':设定一个脚本所能够申请到的最大内存字节数,这有利于写的不好的脚本消耗服务器上的可用内存。@符号代表不输出错误。 
    @ini_set('display_errors', 1); 
    'display_errors':设置错误信息的类别。 
*/

tp5 Session设置
/**
 * session初始化
 * @param array $config
 * @return void
 * @throws \think\Exception
 */
public static function init(array $config = [])
{
      if (empty($config)) {
        $config = Config::get('session');
    }
    // 记录初始化信息
    App::$debug && Log::record('[ SESSION ] INIT ' . var_export($config, true), 'info');
    $isDoStart = false;
    // 是否使用明码在URL中显示SID(会话ID)
    // tp5无默认
    if (isset($config['use_trans_sid'])) {
        ini_set('session.use_trans_sid', $config['use_trans_sid'] ? 1 : 0);
    }

    // 是否自动开启session会话
    // tp5默认false 关闭
    // 参数为1时,程序中不用session_start()来手动开启session也可使用session,
    // 参数为0时,又没手动开启session,则会报错。
    if (!empty($config['auto_start']) && PHP_SESSION_ACTIVE != session_status()) {
        ini_set('session.auto_start', 0);
        $isDoStart = true;
    }

    // 设置session作用域
    // tp5默认'think' $_SESSION['think']
    if (isset($config['prefix']) && ('' === self::$prefix || null === self::$prefix)) {
        self::$prefix = $config['prefix'];
    }
    // var_session_id表示请求session_id变量名
    if (isset($config['var_session_id']) && isset($_REQUEST[$config['var_session_id']])) {
        // 生成session_id
        session_id($_REQUEST[$config['var_session_id']]);
    }
    //
    elseif (isset($config['id']) && !empty($config['id'])) {
        session_id($config['id']);
    }
    if (isset($config['name'])) {
        session_name($config['name']);
    }
    if (isset($config['path'])) {
        session_save_path($config['path']);
    }
    if (isset($config['domain'])) {
        ini_set('session.cookie_domain', $config['domain']);
    }
    if (isset($config['expire'])) {
        ini_set('session.gc_maxlifetime', $config['expire']);
        ini_set('session.cookie_lifetime', $config['expire']);
    }
    //
    // cookie传输是否使用https进行安全传输
    // tp5默认false 不使用
    // 参数为true时:只能依靠HTTPS连接进行安全传输才能传递到服务端(意味着js脚本要模拟发送https请求才能把cookie传递给服务端)
    if (isset($config['secure'])) {
        ini_set('session.cookie_secure', $config['secure']);
    }
    // 是否允许通过程序(JS脚本、Applet等)读取到Cookie信息,这样能有效的防止XSS攻击。
    // tp5是默认true 允许
    if (isset($config['httponly'])) {
        ini_set('session.cookie_httponly', $config['httponly']);
    }
    // 是否把session信息保存至cookie
    // tp5无默认
    if (isset($config['use_cookies'])) {
        ini_set('session.use_cookies', $config['use_cookies'] ? 1 : 0);
    }
    //
    if (isset($config['cache_limiter'])) {
        session_cache_limiter($config['cache_limiter']);
    }
    if (isset($config['cache_expire'])) {
        session_cache_expire($config['cache_expire']);
    }
    if (!empty($config['type'])) {
        // 读取session驱动
        $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\session\\driver\\' . ucwords($config['type']);

        // 检查驱动类
        if (!class_exists($class) || !session_set_save_handler(new $class($config))) {
            throw new ClassNotFoundException('error session handler:' . $class, $class);
        }
    }
    if ($isDoStart) {
        session_start();
        self::$init = true;
    } else {
        self::$init = false;
    }
}

/**
 * session自动启动或者初始化
 * @return void
 */
public static function boot()
{
    if (is_null(self::$init)) {
        self::init();
    } elseif (false === self::$init) {
        if (PHP_SESSION_ACTIVE != session_status()) {
            session_start();
        }
        self::$init = true;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值