您可以通过以下方式执行此操作:
function count_array_values($my_array, $match)
{
$count = 0;
foreach ($my_array as $key => $value)
{
if ($value == $match)
{
$count++;
}
}
return $count;
}
$array = ["hello","bye","hello","John","bye","hello"];
$output =[];
foreach($array as $a){
$output[$a] = count_array_values($array, $a);
}
arsort($output);
print_r($output);
你会得到类似的输出
Array ( [hello] => 3 [bye] => 2 [John] => 1 )我正在开发一个验证变量和常量的函数。
function checkVars($var){
if(isConstant($var)){ <--here is my problem, how do I check if its a Constant and or a string?
return defined($var);
}else{
//use other functions to check if its a valid variable
}
}
有没有办法检查它是字符串还是常量?
编辑: 这背后的想法是节省重复任务的代码行,例如:
if(defined('CONS')){
if(CONS > 0 && CONS !== false){
//and so on..
}
}
这只是一个示例,但您可以使用 4 行代码来验证常量或变量以满足特定应用程序的需求。
这个想法是通过返回 true 或 false 的单个函数调用来保存所有工作:
if(isValid('CONS')){
//do stuff on true
}else{
//do stuff on false
}
慕哥9229398
慕仙森
繁星淼淼