PHP字符串和数组互相转换的操作

php 2023-05-16 585次浏览

前言

PHP的日常开发和处理中,数组和字符串都是绕不过去的两种数据格式,且被频繁使用,下面主要介绍PHP字符串和数组之间互相转换的操作

implode

用字符串连接数组元素

implode(string 字符串连接符, array 数组): string

示例:

<?php

date_default_timezone_set('Asia/Shanghai');

$array = ['lastname', 'email', 'phone'];

var_dump(implode(",", $array)); //string(20) "lastname,email,phone"

var_dump(implode(",", [])); //string(0) ""

var_dump(implode($array)); //string(18) "lastnameemailphone"

explode

字符串使用分隔符生成数组

explode(string 分隔符, string 字符串, int $limit = PHP_INT_MAX): array

$limit 数据生成的元素个数,如果设置为正数,最后一个数组元素则为分割剩余的字符串。如果为负数,则返回除了最后的 -limit 个元素外的所有元素。如果为0,则会被当成1。

示例:

<?php

$str    = "id,name,email,phone,address,create_time";

//示例1:
print_r(explode(",", $str));
/**
输出:
Array
(
   [0] => id
   [1] => name
   [2] => email
   [3] => phone
   [4] => address
   [5] => create_time
)
*/

//示例2:
print_r(explode(",", $str, 3));
/**
输出:
Array
(
   [0] => id
   [1] => name
   [2] => email,phone,address,create_time
)
*/

//示例3:
print_r(explode(",", $str, 0));
/**
输出:
Array
(
   [0] => id,name,email,phone,address,create_time
)
*/

str_split

将字符串转换为数组,这个一般不怎么用到,主要根据长度分割字符串。

str_split(string $string, int $length = 1): array

$string 为空,则返回空数组。$length >= 1

示例

<?php
$str    = "Welcome to Beijing";

print_r(str_split($str));
/**
输出:
    Array
    (
       [0] => W
       [1] => e
       [2] => l
       [3] => c
       [4] => o
       [5] => m
       [6] => e
       [7] =>  
       [8] => t
       [9] => o
       [10] =>  
       [11] => B
       [12] => e
       [13] => i
       [14] => j
       [15] => i
       [16] => n
       [17] => g
    )
*/

print_r(str_split($str, 5));
/**
输出:
    Array
    (
       [0] => Welco
       [1] => me to
       [2] =>  Beij
       [3] => ing
    )
*/

print_r(str_split($str, -2));
// PHP Warning:  str_split(): The length of each segment must be greater than zero in /code/main.php on line 42

print_r(str_split(""));
/**
输出:
    Array
    (
       [0] => 
    )
*/

结语

以上就是PHP字符串和数组互相转换的操作细节分享,更多文章请关注本站其他内容,感谢!

PHP字符串和数组互相转换的操作

喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址