PHP基础学习笔记(常用函数)

字符串

strlen --- 获取字符串长度

php 复制代码
<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
//strlen() 返回的是字符串的字节数,而不是其中字符的数量。
?>

strpos --- 查找字符串首次出现的位置

php 复制代码
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);
echo $pos; //0


// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
echo $pos; //7

str_replace --- 子字符串替换

php 复制代码
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
echo $bodytag; //<body text='black'>

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
echo $onlyconsonants; //Hll Wrld f PHP

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
echo $newphrase; //You should eat pizza, beer, and ice cream every day.

$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;//2

$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';
$newstr = str_replace($order, $replace, $str);
echo $newstr;//Line 1<br />Line 2<br />Line 3<br />Line 4<br />

// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);//F

$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output; //apearpearle pear

数组

count --- 统计数组、Countable 对象中所有元素的数量

php 复制代码
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));//int(3)
$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));//int(3)
?>
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));
// 递归计数
var_dump(count($food, COUNT_RECURSIVE)); //int(8)
// 常规计数
var_dump(count($food)); //int(2)
?>

explode --- 使用一个字符串分割另一个字符串(字符串转数组)

php 复制代码
<?php
// 示例 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

/*
  字符串内不包含分隔字符时,
  会简单返回只有一个原始字符串元素的 array。
*/
$input1 = "hello";
$input2 = "hello,there";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );



$str = 'one|two|three|four';

// 正数的 limit
print_r(explode('|', $str, 1)); //Array([0] => one|two|three|four)
print_r(explode('|', $str, 2)); //Array([0] => one [1] => two|three|four)

// 负数的 limit
print_r(explode('|', $str, -1)); //Array([0] => one [1] => two [2] => three)
print_r(explode('|', $str, -2)); //Array([0] => one [1] => two)
?>

implode --- 用字符串连接数组元素(数组转字符串)

php 复制代码
<?php

$array = ['lastname', 'email', 'phone'];
var_dump(implode(",", $array)); // string(20) "lastname,email,phone"

// Empty string when using an empty array:
var_dump(implode('hello', [])); // string(0) ""

// The separator is optional:
var_dump(implode(['a', 'b', 'c'])); // string(3) "abc"


$elements = array('a', 'b', 'c');
echo "<ul><li>" . implode("</li><li>", $elements) . "</li></ul>"; //<ul><li>a</li><li>b</li><li>c</li></ul>


?>

in_array --- 检查数组中是否存在某个值

php 复制代码
<?php
$os = array("Mac", "NT", "Irix", "Linux");
//区分大小写例子
if (in_array("Irix", $os)) {
    echo "Got Irix"; //Got Irix
}
if (in_array("mac", $os)) {
    echo "Got mac"; 
}
//严格类型检查例子
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict check\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict check\n"; //1.13 found with strict check
}
//数组
$a = [['p', 'h'], ['p', 'r'], 'o'];
if (in_array(['p', 'h'], $a)) {
    echo "'ph' was found\n"; //'ph' was found
}
if (in_array(['f', 'i'], $a)) {
    echo "'fi' was found\n";
}
if (in_array('o', $a)) {
    echo "'o' was found\n"; //'o' was found
}
?>

array_key_exists --- 检查数组里是否有指定的键名或索引

php 复制代码
$search_array = ['first' => 1, 'second' => 4];
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array"; //The 'first' element is in the array
}
array_key_exists() 与 isset() 的对比

isset() 对于数组中为 null 的值不会返回 true,而 array_key_exists() 会。

php 复制代码
<?php
$search_array = array('first' => null, 'second' => 4);
// 返回 true
array_key_exists('first', $search_array); //true
// 返回 false
isset($search_array['first']); //false
?>

array_column --- 返回输入数组中指定列的值

php 复制代码
// 表示从数据库返回的记录集的数组
$records = [
    [
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    [
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ],
    [
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ],
    [
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    ]
);
 
$first_names = array_column($records, 'first_name');
print_r($first_names); /*Array(
 [0] => John
 [1] => Sally
 [2] => Jane 
 [3] => Peter                                                                                                                                                                                                                                                                                                                                      )*/
//从结果集中总取出 last_name 列,用相应的"id"作为键值
// 使用示例 #1 中的 $records 数组
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names); /*Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)*/

$first_names = array_column($records, null, 'id');
print_r($last_names); /*Array
(
    [2135] => Array
        (
            [id] => 2135
            [first_name] => John
            [last_name] => Doe
        )

    [3245] => Array
        (
            [id] => 3245
            [first_name] => Sally
            [last_name] => Smith
        )

    [5342] => Array
        (
            [id] => 5342
            [first_name] => Jane
            [last_name] => Jones
        )

    [5623] => Array
        (
            [id] => 5623
            [first_name] => Peter
            [last_name] => Doe
        )

)*/

array_keys --- 返回数组中所有的键

php 复制代码
$array = array("size" => "XL", "color" => "gold");
var_dump(array_keys($array)) //['size','color']

array_values --- 返回数组中所有的值

php 复制代码
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array)); /*Array
(
    [0] => XL
    [1] => gold
)*/
?>

array_filter --- 使用回调函数过滤数组的元素

php 复制代码
<?php
function odd($var)
{
    // 返回输入整数是否为奇数(单数)
    return $var & 1;
}
function even($var)
{
    // 返回输入整数是否为偶数
    return !($var & 1);
}
$array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
$array2 = [6, 7, 8, 9, 10, 11, 12];
echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));

$array3 = [1,'0', 0, false, null, '','fasle'];
print_r(array_filter($array3)); //[1, false]
?>

array_merge --- 合并一个或多个数组

php 复制代码
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result); /*
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
*/

//如果你想完全保留原有数组并只想新的数组附加到后面,可以使用 + 运算符:
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);/*
array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}
*/
?>

array_slice --- 从数组中取出一段

php 复制代码
$input = array("a", "b", "c", "d", "e");

print_r(array_slice($input, 2));      // [c,d,e]
print_r(array_slice($input, -2, 1));  // [d]
print_r(array_slice($input, 0, 3));   // [a,b,c]

// 注意数组中 key 的不同
print_r(array_slice($input, 2, -1)); // [c,d]
print_r(array_slice($input, 2, -1, true)); // [c,d]

$ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');
print_r(array_slice($ar, 0, 3));/*
Array
(
    [a] => apple
    [b] => banana
    [0] => pear
)
*/
print_r(array_slice($ar, 0, 3, true));/*
Array
(
    [a] => apple
    [b] => banana
    [42] => pear
)
*/
相关推荐
hopetomorrow35 分钟前
学习路之压力测试--jmeter安装教程
学习·jmeter·压力测试
hopetomorrow36 分钟前
学习路之PHP--使用GROUP BY 发生错误 SELECT list is not in GROUP BY clause .......... 解决
开发语言·学习·php
网络安全-杰克44 分钟前
网络安全概论
网络·web安全·php
不是二师兄的八戒1 小时前
本地 PHP 和 Java 开发环境 Docker 化与配置开机自启
java·docker·php
/**书香门第*/1 小时前
Cocos creator 3.8 支持的动画 7
学习·游戏·游戏引擎·游戏程序·cocos2d
美式小田1 小时前
单片机学习笔记 9. 8×8LED点阵屏
笔记·单片机·嵌入式硬件·学习
猫爪笔记2 小时前
前端:HTML (学习笔记)【2】
前端·笔记·学习·html
_不会dp不改名_2 小时前
HCIA笔记3--TCP-UDP-交换机工作原理
笔记·tcp/ip·udp
黑客Ela2 小时前
网络安全中常用浏览器插件、拓展
网络·安全·web安全·网络安全·php
-一杯为品-2 小时前
【51单片机】程序实验5&6.独立按键-矩阵按键
c语言·笔记·学习·51单片机·硬件工程