Reputation: 3855
I am working with CodeIgniter and have created a custom form preferences custom config. In that I have an array that is as follows:
Array
(
[1] => Category 1
[2] => Category 2
[3] => Category 3
[4] => Category 4
[5] => Category 5
)
I am passing that to the view as the var $service_categories
what I'd then like to do is match it to the "value" that is in the database. I.E 5. If it matches then show Category 5
in the view. At the moment I am just showing 5
- This is no good to the user.
The variable $service->service_category
is a number.
The var service
produces:
Array
(
[0] => stdClass Object
(
[service_id] => 3
[organisation_id] => 2
[service_name] => Edited Service 3
[service_description] => This is service 3 provided by
[service_category] => 5
[service_metadata] => Metadata for service 3 - Edited
[service_cost] => 22.00
[service_active] => active
)
)
My current PHP for this is as follows:
if (in_array($service->service_category, $service_categories))
{
echo "Exists";
}
However, the Exists
is not showing in the view. It is showing nothing at all.
Am I doing something wrong with the in_array
method?
Upvotes: 0
Views: 4592
Reputation: 58
in_array()
checks if a value exists in the array. So in_array('Category 1', $service_categories) would work.
However, to check if a key is present in an array, you can use:
if(array_key_exists($service->service_category, $service_categories)) {
echo "Exists";
}
I think, this is what you're looking for.
Upvotes: 4
Reputation: 41080
if (isset($service_categories[$service->service_category])) {
echo "Exists";
}
Upvotes: 2
Reputation: 18859
The variable : $service->service_category is a number.
And that precisely is the problem: your testing to see if "5" is equal to "Category 5", which it is obviously not. Simplest solution would be to prepend the "5" with "Category ":
<?php
$category = 'Category ' . $service->service_category;
if (in_array($category, $service_categories)) {
echo "Exists";
}
EDIT: If you want to check if the array key exists (because '5' => 'Category 5'), this could be achieved with isset( ) or array_key_exists.
<?php
if (array_key_exists ($service->service_category, $service_categories )) {
echo "Exists";
}
// does the same:
if (isset ($service_categories[service->service_category] )) {
echo "Exists";
}
Upvotes: 4