How can you differentiate positive and negative values in a JSON foreach loop in PHP?
To differentiate positive and negative values in a JSON foreach loop in PHP, you can use conditional statements within the loop to check if the value is positive or negative. You can then perform different actions based on the type of value.
$json_data = '{
"numbers": [5, -3, 10, -7, 2]
}';
$data = json_decode($json_data, true);
foreach ($data['numbers'] as $number) {
if ($number > 0) {
echo "Positive value: $number\n";
} else {
echo "Negative value: $number\n";
}
}
Keywords
Related Questions
- What are the implications of not paying attention to the factors affecting performance when reading a file into a string in PHP?
- What are some potential pitfalls of directly using the explode function to process form input before inserting into a database in PHP?
- How can a beginner in PHP programming ensure proper variable usage and prevent errors in their scripts?