Filter Function
The filter function in SwartzDB allows selecting, transforming, and formatting specific fields from a dataset while applying operations like concatenation, case conversion, and arithmetic calculations.
How filter Works
Basic Field Selection
You can extract specific fields from an array:
$filteredData = $sdb->filter($data, ["name", "age"]);
This returns an array containing only the name and age columns.
Applying Operations
Concatenation (concat)
You can merge multiple columns into one:
$filteredData = $sdb->filter($data, [
"full_name" => ["concat" => ["first_name", "s:: ", "last_name"]]
]);
- This merges
first_nameandlast_namewith a space in between. "s:: "is a static value, meaning it's not a column but a fixed space character.
Changing Case (uppercase, lowercase)
You can convert text to uppercase or lowercase:
$filteredData = $sdb->filter($data, [
"upper_name" => ["uppercase" => "name"],
"lower_email" => ["lowercase" => "email"]
]);
"uppercase" => "name"changesnameto uppercase."lowercase" => "email"changesemailto lowercase.
Performing Arithmetic (sum, difference)
You can perform calculations on numerical columns:
$filteredData = $sdb->filter($data, [
"total_price" => ["sum" => ["price", "tax"]],
"profit" => ["difference" => ["revenue", "cost"]]
]);
"sum" => ["price", "tax"]addspriceandtax."difference" => ["revenue", "cost"]subtractscostfromrevenue.
Formatting Dates (date_format)
You can convert dates into a different format:
$filteredData = $sdb->filter($data, [
"formatted_date" => ["date_format" => ["date_column", "d M Y"]]
]);
"date_format" => ["date_column", "d M Y"]convertsdate_columninto"05 Mar 2024"format.
Understanding Static Values (s::)
Any argument in filter is treated as a column or an operation unless it starts with s::.
If an argument starts with "s::", it is a static value (a fixed value, not a column name).
Example:
$filteredData = $sdb->filter($data, [
"greeting" => ["concat" => ["s::Hello, ", "name"]]
]);
"s::Hello, "is a static string."name"is a column.
Example with Numbers
$filteredData = $sdb->filter($data, [
"taxed_price" => ["sum" => ["price", "s::5"]]
]);
"price"is a column."s::5"is a fixed value (adding 5 to the price).
When to Use Filtering?
✅ Use filter when:
- You need to extract specific columns from a dataset.
- You want to format or transform values before use.
- You need computed fields (concatenations, calculations, case changes).
- You need to format dates consistently.
❌ Do NOT use filter when:
- You need to delete rows (use
remove_rowinstead). - You want to update records (use
update_rowinstead).
Conclusion
Filtering in SwartzDB is powerful and flexible, allowing you to extract, modify, and compute data dynamically. Static values (s::) help mix constants with column data, making operations more versatile.