0

I have data from the server: $this->getConfigData('groups') = "1,5,9,10"

I need to make a condition, if one of these id matches the id from the custom group of the current user, then continue, if not, then deny.

I tried this approach, but it doesn't work, tell me how you can implement this logic

$customerGroup = $this->_customerSession->getCustomer()->getGroupId(); -> 1
$array_key = array_keys((array)$this->getConfigData('groups'));        -> {0}[1]
if(!in_array($customerGroup, $array_key)){
    return false;
}

2 Answers 2

1

explode can split a string by a string into an array

Here is a reference sample.

$customerGroup = $this->_customerSession->getCustomer()->getGroupId();//1

$groupsInString = $this->getConfigData('groups'));//(string) "1,5,9,10"
$groupsInArray = explode(",",$this->getConfigData('groups'));//(array) [1,5,9,10]
if(!in_array($customerGroup, $groupsInArray)){
    return false;
}
2
  • What if the string comes empty and the value is null?
    – Alice
    Commented Sep 8, 2020 at 10:01
  • $groupsInArray will be an array containing empty string like [""] Commented Sep 9, 2020 at 5:45
0

You receive a comma separated string from the db. use explode (php native function) and then in_array()

docs for explode https://www.php.net/manual/en/function.explode.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.