Skip to content
Advertisement

(PHP) Search for parts of a string in a vector and return the value

I’m facing the following dilemma, I have a vector that is returned from the bank in the following format:

$vetor = array(0 => 'CR:9090909090909', 1 => 'TR:9090909090909', 2 => 'CP:9090909090909', 3 => 'TP:9090909090909');

I would like to know how to check if in an indeterminate index it contains one of the example codes “CR:” if it has, remove the “CR:” from the value leaving only the value after this code in the case “9090909090909”, remembering that this interaction will be in one foreach for each index of the vector.

Advertisement

Answer

You can choose from two variants.

a) Finding and extracting the single CR code value from $vector array.

function getCode($vector, $type) {
  foreach ($vector as $typeAndCode) {
    list($type1, $code1) = explode(":", $typeAndCode);
    if ($type1 === $type) return $code1;
  }
  return false;
}
$code = getCode($vector, "CR");

b) Writing the extracted CR code value directly into the existing $vector array. (I don’t suppose you will need this variant, but your question wasn’t very clear about it.)

$vector = array_map(function ($typeAndCode) {
  list($type, $code) = explode(":", $typeAndCode);
  return $type === "CR" ? $code : $typeAndCode;
}, $vector);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement