Returning associative array from a prepared statement
$sql = "SELECT * FROM Valor.`Table` WHERE field1 = ? AND field2 = ?;";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $var1, $var2);
$stmt->execute();
$result = $stmt->get_result();
$all_rows = $result->fetch_all(MYSQLI_ASSOC);
foreach($all_rows as $row){
$size = $row['size'];
$alignment = $row['alignment'];; }
$stmt->close();
PHP Recursive Folder Traversing
function getRecursiveFilenames($dirPath) {
// Create a RecursiveDirectoryIterator
$directoryIterator = new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::SKIP_DOTS);
// Flatten the directory structure into a single linear iterator
$iteratorIterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::LEAVES_ONLY);
$filenames = [];
foreach ($iteratorIterator as $file) {
// Use getPathname() to get the full path and filename
$filenames[] = $file->getPathname();
// Alternatively, use getFilename() for just the file name
// $filenames[] = $file->getFilename();
// Or use getRealPath() for the absolute path
// $filenames[] = $file->getRealPath();
// Or use SplFileInfo methods for other info
// $filenames[] = $file->getBasename();
}
return $filenames;
}
Get Files Matching a Pattern and loop through the lines of each file
The pattern captures everything after the first occurrence of ">".
$matches[0] contains the entire matched string, while $matches[1] contains the part captured by the parentheses, which is the text after ">".
The ?? operator is the null coalescing operator. It returns the value on its left if it exists and is not null; otherwise, it returns the value on its right. In this case, if $alignments[$matches[1]] is set and not null, it will be used; otherwise, $matches[1] will be used.
This is a common pattern for looking up a value in an associative array and providing a default if the key is not found.
Test string starts with substring
if (substr($string, 0, strlen($needle)) === $needle)
- OR -
if (strpos($string, $needle) === 0)
- OR -
if (strncmp($string, $needle, strlen($needle)) === 0)
- OR -
if (preg_match('#^' . $needle . '#', $string === 1))
You can use a non-array value for a needle, of course. I decided to use the fanciest example I have so far had a need for.
Even fancier, you can use both a $needles array, and a $replacement array. If both arrays have the same count, then the value at postion X in the needles array will be replaced with the value at psoition X in the replacement array.
Convert html special characters to their html codes.
echo htmlspecialchars("Rock & Roll > alles") . PHP_EOL;