Comparing Data Using FFI
Learn how to compare data using FFI.
It’s important to keep in mind that when we create a C-language data structure using the FFI extension, it exists outside of our PHP application. PHP can interact with the C data to a certain extent. However, for comparison purposes, it’s best to use FFI::memcmp(), as native PHP functions might return inconsistent results.
The two comparison functions available in the FFI extension are summarized here in the following table.
Summary of FFI Class Comparison Methods
FFI Method | Returns | Notes |
|
| Returns |
|
| Operates in much the same manner as the PHP |
FFI::isNull() can be used to determine whether or not the FFI\CData instance is NULL. What is more interesting is FFI::memcmp(). Although this function operates in the same manner as the spaceship operator (<=>), it accepts a third argument that represents how many bytes we wish to include in the comparison. The following example illustrates this usage:
Let’s get into the code.
Lines 3–6: We first define a set of four variables representing
FFI\CDatainstances that can contain up to six characters and populate the instances with sample data.Lines 9–15: Recall that the C language treats character data as an array, so we can’t just directly assign a string, even if using the
cdataproperty. Accordingly, we need to define an anonymous function that populates the instances with letters of the alphabet.Lines 18–22: Next, we use the function to populate the four
FFI\CDatainstances with differing sets of letters.Lines 25–29: We can now use the
FFI::string()...