学习php记录《三》

继续吧。。。

1、string

string的拼接,string是没有+这个运算操作符的,所以是:

$a = 'hello';
$a .='world';

echo $a;

#返回 hello world
$a = 'hello';
$b = $a . 'world';

echo $b;

#结果 "helloworld

要操作string,是通过下标操作的。

 1 <?php
 2 // 取得字符串的第一个字符
 3 $str = 'This is a test.';
 4 $first = $str[0];
 5 
 6 // 取得字符串的第三个字符
 7 $third = $str[2];
 8 
 9 // 取得字符串的最后一个字符
10 $str = 'This is still a test.';
11 $last = $str[strlen($str)-1]; 
12 
13 // 修改字符串的最后一个字符
14 $str = 'Look at the sea';
15 $str[strlen($str)-1] = 'e';
16 
17 ?>

2、array

现在可以直接通过[]定义了~ 感觉又优秀了。

$a = [

'foot' : 'h',

]

删除某个数据

unset($a['foot']);

但是删除后不会重新建立key的索引,附上代码:

<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

删除全部数据:

foreach($a as $i => $value):
    unset($a[$i]);

打印一个数组

print_r($a);

计算数组的大小:

$count = count($array);

如果要重新给value赋值,可在循环中通过引用搞定:

不过这种无脑改应该很少用吧;

$arr = [ 'a'=>'b'];


foreach($arr as $key=>&$value){
    $value= 'test';
}

 再加个官方的实例:

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}

?>
原文地址:https://www.cnblogs.com/-Doraemon/p/4726950.html