if-else

时间:2017-08-02 09:33:29

标签: php

我是PHP的新手,有人可以告诉我这里我做错了什么: -

<?php
$arr = array(
'firstName' => 'Manav',
'lastName' => 'Saxena',
'users' => array(
    array(    'Name' => 'John',
    'age' => 24),
    array( 'Name' => 'Unknown',
    'age' => 22)
));

if($arr['firstName'] == 'Manav'){
    echo "Hello $arr['firstName']";
}

foreach($arr['users'] as $user){
    echo "$user['Name'] is $user['age'] years old!";
}

?>

5 个答案:

答案 0 :(得分:5)

你只是在显示时搞乱了引号。将您的代码更改为:

$arr = array(
'firstName' => 'Manav',
'lastName' => 'Saxena',
'users' => array(
    array(    'Name' => 'John',
    'age' => 24),
    array( 'Name' => 'Unknown',
    'age' => 22)
));

if($arr['firstName'] == 'Manav'){
    echo "Hello $arr[firstName]";
}

foreach($arr['users'] as $user){
    echo "$user[Name] is $user[age] years old!";
}

Demo

答案 1 :(得分:2)

只需concatenate变量,其字符串如下所示

方法1:

if($arr['firstName'] == 'Manav'){
    echo "Hello ".$arr['firstName'];
}

foreach($arr['users'] as $user){
    echo $user['Name']." is ".$user['age']." years old! <br>";
}

方法2:简单删除内部单引号。

    if($arr['firstName'] == 'Manav'){
    echo "Hello $arr[firstName]";
}

foreach($arr['users'] as $user){
    echo "$user[Name] is $user[age] years old! <br>";
}

答案 2 :(得分:1)

你应该这样写,

if($arr['firstName'] == 'Manav'){
    echo "Hello ". $arr['firstName']." ";
}

foreach($arr['users'] as $user){
    echo $user['Name']. "is ". $user['age']." years old!";
}

答案 3 :(得分:1)

它会给你一个解析错误。为了澄清事情,请尝试将值连接到字符串。

请注意,PHP在双引号之间搜索变量,但不在单引号之间搜索。因此,在此使用单引号将为您带来性能优势。

if($arr['firstName'] == 'Manav'){
    echo 'Hello '.$arr['firstName'];
}

foreach($arr['users'] as $user){
    echo $user['Name'].' is '.$user['age'].' years old!';
}

答案 4 :(得分:1)

您有语法错误 用这个替换你的代码:

<?php
    $arr = array(
        'firstName' => 'Manav',
        'lastName' => 'Saxena',
        'users' => array(
            array(    
               'Name' => 'John',
               'age' => 24),
                   array( 
                      'Name' => 'Unknown',
                      'age' => 22
                   )
            )
    );

    if($arr['firstName'] == 'Manav'){
        echo "Hello ".$arr['firstName'];
    }

    foreach($arr['users'] as $user){
        echo $user['Name']." is ".$user['age']." years old!";
    }

?>