How can PHP be used to dynamically determine and display a specific value and its surrounding data in a two-dimensional array?
To dynamically determine and display a specific value and its surrounding data in a two-dimensional array, you can use nested loops to iterate through the array and check each element for the desired value. Once the value is found, you can display it along with its surrounding data by accessing the neighboring elements in the array.
<?php
// Sample two-dimensional array
$array = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
$desiredValue = 5; // Value to search for
foreach ($array as $rowKey => $row) {
foreach ($row as $colKey => $value) {
if ($value == $desiredValue) {
echo "Value: $value\n";
echo "Top: " . ($array[$rowKey-1][$colKey] ?? 'N/A') . "\n";
echo "Bottom: " . ($array[$rowKey+1][$colKey] ?? 'N/A') . "\n";
echo "Left: " . ($array[$rowKey][$colKey-1] ?? 'N/A') . "\n";
echo "Right: " . ($array[$rowKey][$colKey+1] ?? 'N/A') . "\n";
}
}
}
?>
Keywords
Related Questions
- What are common reasons for the "headers already sent" error when using session_start() in PHP?
- What are some best practices for designing a PHP project to handle millions of users simultaneously?
- What are the potential pitfalls of having duplicated content on a multilingual website in terms of SEO and user experience?