I understand that you want to get something like this:
Array
(
[PAC1] => 2
[PAC2] => 0
[PAC3] => 0
)
You could use array_map to apply the same function to each position of your $arrayPacs
and in this function use substr_count to count the number of occurrences of each position of the array in your string:
$arrayPacs = array('PAC1','PAC2','PAC3');
$nombreBuscar = 'esto es una prueba de PAC1 sobre la PAC1';
$map = array_map(function($key) use ($nombreBuscar) {
return substr_count($nombreBuscar, $key);
}, $arrayPacs);
$arrayPacs = array_combine($arrayPacs, $map); // Para mantener las keys de tu $arrayPacs
print_r($arrayPacs);
UPDATE
I update according to the comment of @ Sr1871, more correct with use , but I point out how it works use
vs global
translated from an answer from OS in English:
$global_variable = 1;
$closure = function() use ($global_variable) {
return $global_variable;
};
$closure2 = function() {
global $global_variable;
return $global_variable;
};
$global_variable = 99;
echo $closure(); // Esto mostraría 1
echo $closure2(); // Esto mostraría 99
use
takes the value of $global_variable
at the time of defining the function (closure) while global
takes the current value of $global_variable
at the time of execution.
global
inherits variables from the global scope, while use
inherits them from its local scope.
If we used ... use (&$global_variable)
we would get the same result as with global
.