Reputation: 933
I'm trying to manipulate a text string based on values assigned to a user.
The FULL text string is 'Lists, Items, Cases, Identity and Location' and this is only shown in full against ADMIN.
Each user on the system has access rights. Each right determines what they can and can't do.
So access right a1 = 'Lists'
, b1 = 'Items'
etc...
When the user logs in the page shows what they have access to.
eg:
Welcome $user
You have access to $foo
for the admin user.. this would look like:
Welcome Admin
You have access to Lists, Items, Cases, Identity and Location
So now I'm trying to do the following :
if ($user == 'admin') $foo = 'Lists, Items, Cases, Identity and Location'; // full access
But I need to be able to change the value for each user.
$foo ='';
if (strpos($access,'a1') !== false) $foo .= 'Lists ';
if (strpos($access,'b1') !== false) $foo .= 'Items ';
if (strpos($access,'c1') !== false) $foo .= 'Cases ';
if (strpos($access,'d1') !== false) $foo .= 'Identity ';
if (strpos($access,'e1') !== false) $foo .= 'Location ';
The issue I have with this is the punctuation is messed up. The user Miz has access to a1,b1,c1
When she logs in she gets:
Welcome Miz
You have access to Lists Items Cases
What I'd like it to say is:
Welcome Miz
You have access to Lists, Items and Cases
Can anyone advise the best way to achieve this
Thanks
Upvotes: 2
Views: 64
Reputation: 4896
Something like this will work.
$foo ='';
if (strpos($access,'a1') !== false) $foo .= 'Lists, ';
if (strpos($access,'b1') !== false) $foo .= 'Items, ';
if (strpos($access,'c1') !== false) $foo .= 'Cases, ';
if (strpos($access,'d1') !== false) $foo .= 'Identity, ';
if (strpos($access,'e1') !== false) $foo .= 'Location, ';
$str = rtrim($foo,', '); //remove last ","
echo preg_replace('/,\s([^,]*$)/', ' and $1', $str); //replace last ", " with " and "
Upvotes: 0
Reputation: 12391
Try to use an array and join:
$rights = array();
$foo = '';
if (strpos($access, 'a1') !== false)
$rights[] = 'Lists ';
if (strpos($access, 'b1') !== false)
$rights [] = 'Items ';
if (strpos($access, 'c1') !== false)
$rights [] = 'Cases ';
if (strpos($access, 'd1') !== false && strpos($access, 'e1') !== false) {
$rights[] = "Identity and Location";
} else {
if (strpos($access, 'd1') !== false)
$rights[] = 'Identity ';
if (strpos($access, 'e1') !== false)
$rights[] = 'Location ';
}
echo join(', ', $rights);
EDIT: Based on OP comment in other answer, Identity and Location
handled.
Upvotes: 0
Reputation: 23948
Use implode()
<?php
$arr = array();
if (strpos($access,'a1') !== false) $arr[] = 'Lists ';
if (strpos($access,'b1') !== false) $arr[] = 'Items ';
if (strpos($access,'c1') !== false) $arr[] = 'Cases ';
if (strpos($access,'d1') !== false) $arr[] = 'Identity ';
if (strpos($access,'e1') !== false) $arr[] = 'Location ';
$last = array_pop($arr);
$foo = count($arr) ? implode(", ", $arr) . " AND " . $last : $last;
?>
Upvotes: 3