How to Check if an Array Element Contains a Value from a Whitelist in PHP?

DDD
Release: 2024-11-20 22:30:18
Original
201 people have browsed it

How to Check if an Array Element Contains a Value from a Whitelist in PHP?

Verifying the Presence of Whitelisted Values in Array Elements

The task at hand is to determine whether a specific element of an array contains a value that is included in a predetermined whitelist. For instance, in this case, we want to verify if the value of $something['say'] is either 'bla' or 'omg'.

To accomplish this, we can leverage the PHP in_array() function. This function evaluates whether a given value exists within an array. Let's break down how this works:

<?php
$whitelist = ['bla', 'omg'];
$something = array('say' => 'bla', 'say' => 'omg');

if(in_array('bla', $something['say'])) {
    echo "Element contains bla";
}
?>
Copy after login

In this script, we define a whitelist array containing the allowed values. We then iterate through each element of $something['say'] using in_array('bla', $something['say']). If 'bla' is found within the current element, it indicates a match and triggers the "Element contains bla" message.

This approach can be modified to check for multiple values simultaneously by passing an array of whitelisted values as the second argument to in_array(). The function will return true if any of the values in the whitelist are present in the input array element.

The above is the detailed content of How to Check if an Array Element Contains a Value from a Whitelist in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template