Reputation: 1189
I have an array $categories
as follows;
Array
(
[0] => Array
(
[category_id] => 0
)
[1] => Array
(
[category_id] => 3
)
)
I want to apply some condition in foreach as follows;
Note: following condition is not working;
foreach ($categories as $key=> $category)
{
if($category['category_id']===0)
{
$categories[$key]['category_name'] = 'NA';
}
else
{
$categories[$key]['category_name'] = 'something';
}
}
so my expected result will become;
Array
(
[0] => Array
(
[category_id] => 0
[category_name] => NA
)
[1] => Array
(
[category_id] => 3
[category_id] => something
)
)
Upvotes: 0
Views: 421
Reputation: 1436
In the array there is possible that 0
could be string you are checking with ===
operator which will match string with its datatype also.
You can check its datatype if needed using gettype($value)
.
For current issue try this:
/* Compare value without checking its datatype */
if($category['category_id'] == 0) /* replace === to == */
{
$categories[$key]['category_name'] = 'NA';
}
else
{
$categories[$key]['category_name'] = 'something';
}
Upvotes: 2