在 PHP 中将 if then 与多个条件以及运算符一起使用

Using if then with multiple conditions along with operators in PHP

有一个下拉菜单显示 select playlist。

每个播放列表中都有一定数量的歌曲。

例如:播放列表包括:POP(歌曲总数= 3)、ROCK(歌曲= 4)、Jaz(歌曲= 5)、Classical(歌曲= 6)

假设用户选择了一个播放列表 - POP 并在文本框(歌曲编号框)中键入数字 3,然后当单击“搜索”按钮时,它将从音频文件夹(如果存在)中打开 POP3.mp3 文件,否则它将显示 数据库中不可用的歌曲

And 如果用户选择 POP 并在歌曲编号框中键入 4,它应该显示 无效歌曲编号

是这样的!!!但是这段代码不起作用我不知道错误在哪里。请指正!!

<?php
$valid = ['POP' => 3, 'ROCK' => 5, 'JAZZ' => 5];
// User selected genre and songnumber
$PlaylistName = 'ROCK'; // Note: I will get this value from dropdown in HTML
$songNumber = 5; // Note: I will get this value from textbox in HTML form
$song = $PlaylistName . $songNumber . '.mp3';
$file_pointer = './audio/' . $song;

foreach ($valid as $genre => $numberSongs) {
    if ($PlaylistName === $genre && $songNumber <= $numberSongs) {
        if (file_exists($file_pointer)) {
            header("Location: ./audio/" . $song);
            exit();
        } else {
            SongNotavailable();
        }
    } else {
        InvalidSongnumber();
    }
}

function InvalidSongnumber()
{
    echo "Invalid Song number!";
}

function SongNotavailable()
{
    echo '<span style="color: red;"/>Sorry! This song is not available on our database.</span>';
}
?>

// This gives result: Invalid Song number!Sorry! This song is not available on our database. Invalid Song number!

// But the valid answer is only Sorry! This song is not available on our database.

// So I need a correction in my code so that I can get only a valid result, not all results together

您的问题是您处于一个循环中并且您正在迭代 valid 中的每个条目。您应该只验证一次传入的数据。

<?php

$valid = [
    'POP' => 3, 
    'ROCK' => 5, 
    'JAZZ' => 5
];

// Test data
$PlaylistName = 'ROCK'; 
$songNumber = 5;

// Check the playlist exists
if (!array_key_exists($PlaylistName, $valid)) {
    echo 'Invalid playlist provided.';
    exit;
}

// Check the song number is not greater than what is allowed
if ((int)$songNumber > $valid[$PlaylistName]) {
    echo  'Invalid song number provided.';
    exit;
}

$song = $PlaylistName . $songNumber . '.mp3';
$file_pointer = './audio/' . $song;

// Check the file exists on disk
if (!file_exists($file_pointer)) {
    echo '<span style="color: red;"/>Sorry! This song is not available on our database.</span>';
    exit;
}

// We now know the song is valid.
header("Location: ./audio/" . $song);
exit();