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"; } ?>
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!