参考 - 这个符号在PHP中意味着什么?

时间:2010-09-17 16:24:07

标签: php operators symbols php-5.3

这是什么?

这是一系列关于PHP语法的问题。这也是社区Wiki,因此邀请每个人参与维护此列表。

为什么会这样?

以前很难找到有关运算符和其他语法标记的问题.¹
主要思想是链接到Stack Overflow上的现有问题,因此我们更容易引用它们,而不是复制PHP手册中的内容。

注意:自2013年1月起,Stack Overflow does support special characters。只需用引号括住搜索字词,例如: [php] "==" vs "==="

我该怎么办?

如果您因为提出这样的问题而被某人指向此处,请在下面找到具体的语法。 PHP manual的链接页面以及链接的问题可能会回答您的问题。如果是这样,我们鼓励您提出答案。此列表并不代替其他人提供的帮助。

列表

如果下面没有列出您的特定令牌,您可以在List of Parser Tokens

中找到它

& Bitwise OperatorsReferences


=& References


&= Bitwise Operators


&& Logical Operators


% Arithmetic Operators


!! Logical Operators


@ Error Control Operators


?: Ternary Operator


?? Null Coalesce Operator(自PHP 7起)


?string ?int ?array ?bool ?float Nullable return type declaration(自PHP 7.1起)


: Alternative syntax for control structuresTernary Operator


:: Scope Resolution Operator


\ Namespaces


-> Classes And Objects


=> Arrays


^ Bitwise Operators


>> Bitwise Operators


<< Bitwise Operators


<<< Heredoc or Nowdoc


= Assignment Operators


== Comparison Operators


=== Comparison Operators


!== Comparison Operators


!= Comparison Operators


<> Comparison Operators


<=> Comparison Operators(自PHP 7.0开始)


| Bitwise Operators


|| Logical Operators


~ Bitwise Operators


+ Arithmetic OperatorsArray Operators


+=-= Assignment Operators


++-- Incrementing/Decrementing Operators


.= Assignment Operators


. String Operators


, Function Arguments

, Variable Declarations


$$ Variable Variables


` Execution Operator


<?= Short Open Tags


[] Arrays(PHP 5.4以来的短语法)


<? Opening and Closing tags


... Argument unpacking(自PHP 5.6开始)


** Exponentiation(自PHP 5.6开始)


# One-line shell-style comment


:? Nullable return types


20 个答案:

答案 0 :(得分:1064)

<强> Incrementing / Decrementing Operators

++增量运算符

--递减运算符

Example    Name              Effect
---------------------------------------------------------------------
++$a       Pre-increment     Increments $a by one, then returns $a.
$a++       Post-increment    Returns $a, then increments $a by one.
--$a       Pre-decrement     Decrements $a by one, then returns $a.
$a--       Post-decrement    Returns $a, then decrements $a by one.

这些可以在变量之前或之后进行。

如果放在变量之前,则对变量 first 进行递增/递减操作,然后返回结果。如果放在变量之后,返回 first 变量,则完成递增/递减操作。

例如:

$apples = 10;
for ($i = 0; $i < 10; ++$i) {
    echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}

<强> Live example

在上面使用++$i的情况下,因为它更快。 $i++会有相同的结果。

预增量稍微快一点,因为它确实增加了变量,然后'返回'结果。后增量创建一个特殊变量,在那里复制第一个变量的值,并且只有在使用第一个变量之后,才用第二个变量替换它的值。

但是,您必须使用$apples--,因为首先,您要显示当前的苹果数量,然后然后要从中减去一个苹果。

您还可以在PHP中增加字母:

$i = "a";
while ($i < "c") {
    echo $i++;
}

到达z后,接下来是aa,依此类推。

  

请注意,字符变量可以递增但不会递减,即使只支持纯ASCII字符(a-z和A-Z)。


Stack Overflow帖子:

答案 1 :(得分:407)

按位运算符

有点什么?位是1或0的表示。基本上是OFF(0)和ON(1)

什么是字节?一个字节由8位组成,一个字节的最高值为255,这意味着每个位都被置位。我们将研究为什么字节的最大值为255。

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------

1字节的表示

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255(1字节)

一些更好理解的例子

“AND”运算符:&

$a =  9;
$b = 10;
echo $a & $b;

这会输出数字8.为什么?好吧,让我们看一下使用我们的表格示例。

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
-------------------------------------------
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
------------------------------------------- 
|      &     |   0|  0|  0|  0| 1| 0| 0| 0|
------------------------------------------- 

所以你可以从表中看到他们共同分享的唯一一位是8位。

第二个例子

$a =  36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111

两个共享位是32和4,加在一起时返回36。

“或”运算符:|

$a =  9;
$b = 10;
echo $a | $b;

这会输出数字11.为什么?

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
-------------------------------------------
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
------------------------------------------- 
|      |     |   0|  0|  0|  0| 1| 0| 1| 1|
-------------------------------------------

您会注意到我们在8列,2列和1列中设置了3位。添加它们:8 + 2 + 1 = 11.

答案 2 :(得分:255)

_ Alias for gettext()

_()中的下划线字符“_”是gettext()函数的别名。

答案 3 :(得分:246)

Syntax    Name             Description

x == y    Equality         True if x and y have the same key/value pairs
x != y    Inequality       True if x is not equal to y
x === y   Identity         True if x and y have the same key/value pairs
                            in the same order and of the same types
x !== y   Non-identity     True if x is not identical to y
++ x      Pre-increment    Increments x by one, then returns x
x ++      Post-increment   Returns x, then increments x by one
-- x      Pre-decrement    Decrements x by one, then returns x
x --      Post-decrement   Returns x, then decrements x by one
x and y   And              True if both x and y are true x=6 y=3
                           (x < 10 and y > 1) returns true 
x && y    And              True if both x and y are true x=6 y=3
                           (x < 10 && y > 1) returns true
a . b     Concatenation    Concatenate two strings: "Hi" . "Ha"

答案 4 :(得分:235)

<=>太空飞船运营商

在PHP 7中添加

spaceship operator <=>是PHP 7中添加的最新比较运算符。它是一个非关联二元运算符,其优先级与相等运算符相同({{1 }},==!====)。该运算符允许在左手操作数和右手操作数之间进行更简单的三向比较。

运算符导致整数表达式为:

    两个操作数相等时
  • !==
  • 当左侧操作数小于右侧操作数时小于0
  • 当左侧操作数大于右侧操作数时大于0

e.g。

0

使用此运算符的一个很好的实际应用是比较类型的回调,它基于两个值之间的三向比较,预期返回零,负或正整数。传递给usort的比较函数就是这样一个例子。

在PHP 7之前,你会写...

1 <=> 1; // 0
1 <=> 2; // -1
2 <=> 1; // 1

从PHP 7开始,你可以写...

$arr = [4,2,1,3];

usort($arr, function ($a, $b) {
    if ($a < $b) {
        return -1;
    } elseif ($a > $b) {
        return 1;
    } else {
        return 0;
    }
});

答案 5 :(得分:216)

魔术常数:虽然这些不仅仅是符号,而是此令牌系列的重要组成部分。有八个魔法常数会根据它们的使用位置而改变。

__LINE__:文件的当前行号。

__FILE__:文件的完整路径和文件名。如果在include中使用,则返回包含文件的名称。从PHP 4.0.2开始,__FILE__总是包含已解析符号链接的绝对路径,而在旧版本中,它在某些情况下包含相对路径。

__DIR__:文件的目录。如果在include中使用,则返回包含文件的目录。这相当于dirname(__FILE__)。除非它是根目录,否则此目录名称没有尾部斜杠。 (在PHP 5.3.0中添加。)

__FUNCTION__:函数名称。 (在PHP 4.3.0中添加)从PHP 5开始,此常量返回声明的函数名称(区分大小写)。在PHP 4中,它的值总是小写的。

__CLASS__:班级名称。 (在PHP 4.3.0中添加)从PHP 5开始,此常量返回声明的类名(区分大小写)。在PHP 4中,它的值总是小写的。类名包括声明它的名称空间(例如Foo\Bar)。请注意,从PHP 5.4开始,__CLASS__也适用于特征。在特征方法中使用时,__CLASS__是使用特征的类的名称。

__TRAIT__:特征名称。 (在PHP 5.4.0中添加)从PHP 5.4开始,此常量返回声明的特征(区分大小写)。特征名称包括声明它的名称空间(例如Foo\Bar)。

__METHOD__:类方法名称。 (在PHP 5.0.0中添加)方法名称在声明时返回(区分大小写)。

__NAMESPACE__:当前命名空间的名称(区分大小写)。此常量在编译时定义(在PHP 5.3.0中添加)。

Source

答案 6 :(得分:117)

operators in PHP的概述:

Logical Operators:

  • $ a&amp;&amp; $ b:如果$ a和$ b都为TRUE,则为TRUE。
  • $ a || $ b:如果$ a或$ b为TRUE,则为TRUE。
  • $ a xor $ b:如果$ a或$ b为TRUE,则为TRUE,但不是两者都为。
  • ! $ a:如果$ a不为TRUE,则为TRUE。
  • $ a和$ b:如果$ a和$ b都为TRUE,则为TRUE。
  • $ a或$ b:如果$ a或$ b为TRUE,则为TRUE。

Comparison operators:

  • $ a == $ b:如果类型杂耍后$ a等于$ b,则为TRUE。
  • $ a === $ b:如果$ a等于$ b,则为TRUE,且它们属于同一类型。
  • $ a!= $ b:如果$ j在类型杂耍后不等于$ b,则为TRUE。
  • $ a&lt;&gt; $ b:如果在类型杂耍之后$ a不等于$ b,则为TRUE。
  • $ a!== $ b:如果$ a不等于$ b,则为TRUE,或者它们的类型不同。
  • $ a&lt; $ b :如果$ a严格低于$ b,则为TRUE。
  • $ a&gt; $ b :如果$ a严格大于$ b,则为TRUE。
  • $ a&lt; = $ b :如果$ a小于或等于$ b,则为TRUE。
  • $ a&gt; = $ b :如果$ a大于或等于$ b,则为TRUE。
  • $ a&lt; =&gt; $ b :当$ a分别小于,等于或大于$ b时,小于,等于或大于零的整数。从PHP 7开始提供。
  • $ a? $ b:$ c :如果$ a返回$ b,则返回$ c(ternary operator
  • $ a ?? $ c :与$ a相同? $ a:$ c(null coalescing operator - 需要PHP&gt; = 7)

Arithmetic Operators:

  • - $ a :$ a。
  • 的对面
  • $ a + $ b :$ a和$ b的总和。
  • $ a - $ b :$ a和$ b的差异。
  • $ a * $ b :$ a和$ b的产品。
  • $ a / $ b :$ a和$ b的商数。
  • $ a%$ b :$ a的剩余除以$ b。
  • $ a ** $ b :将$ a筹集到$ b&#39;(在PHP 5.6中引入)

Incrementing/Decrementing Operators:

  • ++ $ a :将$ a递增1,然后返回$ a。
  • $ a ++ :返回$ a,然后将$ a递增1。
  • - $ a :将$ a递减1,然后返回$ a。
  • $ a - :返回$ a,然后将$ a减1。

Bitwise Operators:

  • $ a&amp; $ b :设置$ a和$ b中设置的位。
  • $ a | $ b :设置以$ a或$ b设置的位。
  • $ a ^ $ b :设置$ a或$ b但不是两者都设置的位。
  • 〜$ a :未设置$ a中设置的位,反之亦然。
  • $ a&lt;&lt; $ b :将$ a $ b步的位移到左边(每一步意味着&#34;乘以2&#34;)
  • $ a&gt;&gt; $ b :将$ a $ b步的位移到右边(每一步意味着&#34;除以2&#34;)

String Operators:

  • $ a。 $ b :$ a和$ b的连接。

Array Operators:

  • $ a + $ b :$ a和$ b的联盟。
  • $ a == $ b :如果$ a和$ b具有相同的键/值对,则为TRUE。
  • $ a === $ b :如果$ a和$ b在相同的顺序和相同类型中具有相同的键/值对,则为TRUE。
  • $ a!= $ b :如果$ a不等于$ b,则为TRUE。
  • $ a&lt;&gt; $ b :如果$ a不等于$ b,则为TRUE。
  • $ a!== $ b :如果$ a与$ b不同,则为TRUE。

Assignment Operators:

  • $ a = $ b :$ b的值已分配给$ a
  • $ a + = $ b :与$ a = $ a + $ b相同
  • $ a - = $ b :与$ a = $ a相同 - $ b
  • $ a * = $ b :与$ a = $ a * $ b相同
  • $ a / = $ b :与$ a = $ a / $ b相同
  • $ a%= $ b :与$ a = $ a%$ b相同
  • $ a ** = $ b :与$ a = $ a ** $ b相同
  • $ a。= $ b :与$ a = $ a相同。 $ B
  • $ a&amp; = $ b :与$ a = $ a&amp;相同$ B
  • $ a | = $ b :与$ a = $ a |相同$ B
  • $ a ^ = $ b :与$ a = $ a ^ $ b相同
  • $ a&lt;&lt; = $ b :与$ a = $ a&lt;&lt;相同$ B
  • $ a&gt;&gt; = $ b :与$ a = $ a&gt;&gt;相同$ B

注意

and运算符和or运算符的优先级低于赋值运算符=

这意味着$a = true and false;相当于($a = true) and false

在大多数情况下,您可能希望使用 && || ,其行为方式与C,Java等语言相同或JavaScript。

答案 7 :(得分:92)

太空飞船运营商<=> (在PHP 7中添加)

Examples for <=> Spaceship operator (PHP 7, Source: PHP Manual):

整数,浮点数,字符串,数组和&amp;对象用于变量的三向比较。

// Integers
echo 10 <=> 10; // 0
echo 10 <=> 20; // -1
echo 20 <=> 10; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
// Comparison is case-sensitive
echo "B" <=> "a"; // -1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "c"]; 
echo $a <=> $b; // -1

$a = (object) ["a" => "c"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 1

// only values are compared
$a = (object) ["a" => "b"]; 
$b = (object) ["b" => "b"]; 
echo $a <=> $b; // 1

答案 8 :(得分:56)

空合并运算符(??)

在PHP 7.0中添加了此运算符,用于需要将三元运算符与isset()结合使用的常见情况。它返回第一个操作数(如果存在且不是NULL;否则它返回第二个操作数。

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

答案 9 :(得分:56)

PHP字符串: PHP字符串可以用四种方式指定,而不仅仅是两种方式:

1)单引号字符串:

$string = 'This is my string'; // print This is my string

2)双引号字符串:

$str = 'string';

$string = "This is my $str"; // print This is my string

3)Heredoc:

$string = <<<EOD
This is my string
EOD; // print This is my string

4)Nowdoc(自PHP 5.3.0开始):

$string = <<<'END_OF_STRING'
    This is my string 
END_OF_STRING; // print This is my string

答案 10 :(得分:40)

<强>问题:

=>是什么意思?

答案:

=>我们人类决定使用的符号来分离关联数组中的"Key" => "Value"对。

<强>阐述:

要理解这一点,我们必须知道关联数组是什么。传统程序员想到一个数组(PHP中的 )时出现的第一件事就是:

$myArray1 = array(2016, "hello", 33);//option 1

$myArray2 = [2016, "hello", 33];//option 2

$myArray3 = [];//option 3
$myArray3[] = 2016; 
$myArray3[] = "hello"; 
$myArray3[] = 33;

如果我们想在代码的后面部分调用数组,我们可以这样做:

echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello

到目前为止一切顺利。但是,作为人类,我们可能会发现很难记住数组的索引[0] 2016的值,数组的索引[1]问候,数组的索引[2]是一个简单的整数值。我们接下来的替代方案是使用所谓的关联数组。关联数组与顺序数组有一些差异 (这是之前的案例,因为它们增加了预定序列中使用的索引,通过对每个后续值递增1来

差异(顺序和关联数组之间的 ):

  • 在引用关联数组的过程中,您不仅要包含要放入数组中的value,还要放置索引值(称为{{ 1}})在代码的后面部分调用数组时要使用的。在其声明中使用以下语法:key

  • 使用关联数组时,"key" => "value"值将放在数组的索引中以检索所需的key

例如:

value

现在,要获得与以前相同的输出, $myArray1 = array( "Year" => 2016, "Greetings" => "hello", "Integer_value" => 33);//option 1 $myArray2 = [ "Year" => 2016, "Greetings" => "hello", "Integer_value" => 33];//option 2 $myArray3 = [];//option 3 $myArray3["Year"] = 2016; $myArray3["Greetings"] = "hello"; $myArray3["Integer_value"] = 33; 值将用于数组索引中:

key

最终要点:

因此,从上面的示例中,很容易看到echo $myArray1["Greetings"];// output: hello echo $myArray2["Greetings"];// output: hello echo $myArray3["Greetings"];// output: hello 符号用于表示每个=>key对之间的关​​联数组的关系。一个数组 DURING 在数组中启动值。

答案 11 :(得分:30)

<强>问题

“&amp;”是什么在PHP中意味着什么?

PHP“&amp;”操作

一旦我们习惯了,生活会更轻松..(仔细查看下面的例子)

&amp; 通常会检查在$ a和$ b中设置的位。

  你有没有注意到这些电话是如何运作的?

   error_reporting(E_ERROR | E_WARNING | E_PARSE);
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    error_reporting(E_ALL & ~E_NOTICE);
    error_reporting(E_ALL);

所以上面的所有内容都是按位运算符和位的游戏。

这些的一个有用的例子是如下所示的简单配置,因此单个整数字段可以为您存储数千个组合。

大多数人已经阅读过这些文档,但没有使用这些按位运算符的实际用例。

你爱的例子

<?php

class Config {

    // our constants must be 1,2,4,8,16,32,64 ....so on
    const TYPE_CAT=1;
    const TYPE_DOG=2;
    const TYPE_LION=4;
    const TYPE_RAT=8;
    const TYPE_BIRD=16;
    const TYPE_ALL=31;

    private $config;

    public function __construct($config){
        $this->config=$config;

        if($this->is(Config::TYPE_CAT)){
            echo 'cat ';
        }
        if($this->is(Config::TYPE_DOG)){
            echo 'dog ';
        }
        if($this->is(Config::TYPE_RAT)){
            echo 'rat ';
        }
        if($this->is(Config::TYPE_LION)){
            echo 'lion ';
        }
        if($this->is(Config::TYPE_BIRD)){
            echo 'bird ';
        }
        echo "\n";
    }

    private function is($value){
        return $this->config & $value;
    }
}

new Config(Config::TYPE_ALL);
// cat dog rat lion bird
new Config(Config::TYPE_BIRD);
//bird
new Config(Config::TYPE_BIRD | Config::TYPE_DOG);
//dog bird
new Config(Config::TYPE_ALL & ~Config::TYPE_DOG & ~Config::TYPE_CAT);
//rat lion bird

答案 12 :(得分:24)

==用于检查等式,不用考虑变量数据类型

===用于检查 变量值*和**数据类型

的相等性

实施例

$a = 5

  1. if ($a == 5) - 将评估为真

  2. if ($a == '5') - 将评估为true,因为在比较这两个值时,php会在内部将该字符串值转换为整数,然后比较这两个值

  3. if ($a === 5) - 将评估为真

  4. if ($a === '5') - 将评估为false,因为值为5,但此值5不是整数。

答案 13 :(得分:23)

Null Coalesce Operator php

对于需要与isset()一起使用三元组的常见情况,已将空合并运算符(??)添加到PHP7中。它返回第一个操作数(如果存在)并且不为NULL,否则返回其第二个操作数,如下例所示:

$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; 

答案 14 :(得分:21)

Null Coalesce运算符“??” (在PHP 7中添加)

不是运营商最糟糕的名字,但PHP 7引入了相当方便的空合并,所以我想我会分享一个例子。

在PHP 5中,我们已经有了一个三元运算符,它测试一个值,然后返回第二个元素(如果返回true)和第三个元素(如果不返回):

echo $count ? $count : 10; // outputs 10

还有一个简写,允许你跳过第二个元素,如果它与第一个元素相同:echo $ count?:10; //也输出10

在PHP 7中我们另外得到了??运算符,而不是表示极端混乱,而不是我通常会一起使用两个问号,而是允许我们将一串值链接在一起。从左到右读取,存在且不为null的第一个值是将返回的值。

// $a is not set
$b = 16;

echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16

此构造可用于优先考虑可能来自用户输入或现有配置的一个或多个值,并且如果缺少该配置,则安全地回退到给定的默认值。这是一个小功能,但我知道,只要我的应用程序升级到PHP 7,我就会使用它。

答案 15 :(得分:7)

可空的返回类型声明

PHP 7添加了对返回类型声明的支持。与参数类型声明类似,返回类型声明指定将从函数返回的值的类型。返回类型声明和参数类型声明都可以使用相同的类型。

严格键入也会对返回类型声明产生影响。在默认的弱模式下,如果返回的值还不是该类型,则将其强制为正确的类型。在强模式下,返回的值必须是正确的类型,否则将引发TypeError。

从PHP 7.1.0开始,可以通过在类型名称前添加问号(?)来将返回值标记为可为空。这表示该函数返回指定的类型或NULL。

<?php
function get_item(): ?string {
    if (isset($_GET['item'])) {
        return $_GET['item'];
    } else {
        return null;
    }
}
?>

Source

答案 16 :(得分:6)

?-> NullSafe运算符

在PHP 8.0中添加

它是NullSafe Operator,如果您尝试调用函数或从null获取值,它将返回null。 Nullsafe运算符可以被链接,并且可以在方法和属性上使用。

$objDrive = null;
$drive = $objDrive?->func?->getDriver()?->value; //return null
$drive = $objDrive->func->getDriver()->value; // Error: Trying to get property 'func' of non-object

Nullsafe运算符不适用于数组键:

$drive['admin']?->getDriver()?->value //Warning: Trying to access array offset on value of type null

$drive = [];
$drive['admin']?->getAddress()?->value //Warning: Undefined array key "admin"

答案 17 :(得分:4)

作为Splat运算符的三个DOTS(...)(自PHP 5.6起)

PHP有一个运算符“ ...”(三个点),称为Splat运算符。它用于在函数中传递任意数量的参数,这种类型的函数称为可变函数。让我们以使用“ ...”(三个点)为例。

  

示例1:

<?php
function calculateNumbers(...$params){
    $total = 0;
    foreach($params as $v){
        $total = $total + $v;
    }
    return $total;
}

echo calculateNumbers(10, 20, 30, 40, 50);

//Output 150
?>

在使用“…”时,calculateNumbers()函数的每个参数都将$ params作为数组传递。

使用“…”运算符的方式有很多。下面是一些示例:

  

示例2:

<?php
function calculateNumbers($no1, $no2, $no3, $no4, $no5){
    $total = $no1 + $no2 + $no3 + $no4 + $no5;
    return $total;
}

$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers(...$numbers);

//Output 150
?>
  

示例3:

<?php
function calculateNumbers(...$params){
    $total = 0;
    foreach($params as $v){
        $total = $total + $v;
    }
    return $total;
}
$no1 = 70;
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers($no1, ...$numbers);

//Output 220
?>
  

示例4:

<?php
function calculateNumbers(...$params){
    $total = 0;
    foreach($params as $v){
        $total = $total + $v;
    }
    return $total;
}

$numbers1 = array(10, 20, 30, 40, 50);
$numbers2 = array(100, 200, 300, 400, 500);
echo calculateNumbers(...$numbers1, ...$numbers2);

//Output 1650

?>

答案 18 :(得分:4)

NullSafe运算符“?->”(可能自PHP8起)

在PHP8中,该新运算符已被接受,您可以找到文档here?->NullSafe Operator,如果您尝试调用函数或从null获取值,它将返回null ...

示例:

<?php
$obj = null;
$obj = $obj?->attr; //return null
$obj = ?->funct(); // return null
$obj = $objDrive->attr; // Error: Trying to get property 'attr' of non-object
?>

答案 19 :(得分:0)

PHP 数组:

数组是一种数据结构,将一个或多个相似类型的值存储在一个值中

• 数字数组 - 具有数字索引的数组。值以线性方式存储和访问。

• 关联数组- 以字符串作为索引的数组。这将元素值与键值关联存储,而不是按照严格的线性索引顺序存储。

• 多维数组 - 使用多个索引访问包含一个或多个数组和值的数组 数值数组

这些数组可以存储数字、字符串和任何对象,但它们的索引将由数字表示。默认情况下,数组索引从零开始。

示例:

<html>
   <body>
   
      <?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

输出:

Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
Value is one 
Value is two 
Value is three 
Value is four 
Value is five

关联数组

关联数组在功能方面与数值数组非常相似,但它们的索引不同。关联数组会将它们的索引作为字符串,以便您可以在键和值之间建立强关联。

示例:

<html>
   <body>
      
      <?php
         /* First method to associate create array. */
         $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
         
         /* Second method to create array. */
         $salaries['mohammad'] = "high";
         $salaries['qadir'] = "medium";
         $salaries['zara'] = "low";
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
      ?>
   
   </body>
</html>

输出:

Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

多维数组

一个多维数组,主数组中的每个元素也可以是一个数组。并且子数组中的每个元素都可以是一个数组,依此类推。使用多个索引访问多维数组中的值。

示例

<html>
   <body>
      
      <?php
         $marks = array( 
            "mohammad" => array (
               "physics" => 35,
               "maths" => 30,   
               "chemistry" => 39
            ),
            
            "qadir" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
            
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
         
         /* Accessing multi-dimensional array values */
         echo "Marks for mohammad in physics : " ;
         echo $marks['mohammad']['physics'] . "<br />"; 
         
         echo "Marks for qadir in maths : ";
         echo $marks['qadir']['maths'] . "<br />"; 
         
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />"; 
      ?>
   
   </body>
</html>

输出:

Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

PHP 数组函数

  • array() -> 创建一个数组

  • array_change_key_case() -> 将数组中的所有键更改为小写或大写

  • array_chunk() -> 将数组拆分为数组块 array_column() -> 返回输入数组中单列的值

  • array_combine() -> 使用一个“键”数组和一个“值”数组中的元素创建一个数组

  • array_count_values() -> 计算一个数组的所有值

  • array_diff() -> 比较数组,并返回差异(仅比较值)

  • array_diff_assoc() -> 比较数组,并返回差异(比较键和值)

  • array_diff_key() -> 比较数组,并返回差异(仅比较键)

  • array_diff_uassoc() -> 比较数组,并返回差异(比较键和值,使用用户定义的键比较函数)

  • array_diff_ukey() -> 比较数组,并返回差异(仅比较键,使用用户定义的键比较函数)

  • array_fill() -> 用值填充数组

  • array_fill_keys() -> 用值填充数组,指定键

  • array_filter() -> 使用回调函数过滤数组的值

  • array_flip() -> 翻转/交换所有键及其在数组中的关联值

  • array_intersect() -> 比较数组,并返回匹配项(仅比较值)

  • array_intersect_assoc() -> 比较数组并返回匹配项(比较键和值)

  • array_intersect_key() -> 比较数组,并返回匹配项(仅比较键)

  • array_intersect_uassoc() -> 比较数组,并返回匹配项(比较键和值,使用用户定义的键比较函数)

  • array_intersect_ukey() -> 比较数组,并返回匹配项(仅比较键,使用用户定义的键比较函数)

  • array_key_exists() -> 检查指定的键是否存在于数组中

  • array_keys() -> 返回数组的所有键

  • array_map() -> 将数组的每个值发送到用户创建的函数,该函数返回新值

  • array_merge() -> 将一个或多个数组合并为一个数组

  • array_merge_recursive() -> 将一个或多个数组递归合并为一个数组

  • array_multisort() -> 对多维或多维数组进行排序