I'm new to php and I' still learning its logics. I have an array like this:
$arr=array("1.1"=>"Val", "1.1.1"=>"Val", "1.1.1.1"=>"Val",
"1.1.1.2"=>"Val", "1.1.1.3"=>"Val",
"1.1.1.4"=>"Val", "1.1.2"=>"Val", "1.1.3"=>"Val",
"1.1.4"=>"Val", "1.1.5"=>"Val", "1.1.6"=>"Val",
"1.1.7"=>"Val", "1.1.8"=>"Val", "1.1.9"=>"Val",
"1.1.10"=>"Val", "1.1.11"=>"Val");
I need to filter it extracting items of the group "1.1.1"
So, my result should be:
$arr2=array("1.1.1"=>"Val", "1.1.1.1"=>"Val",
"1.1.1.2"=>"Val", "1.1.1.3"=>"Val",
"1.1.1.4"=>"Val");
I wrote the following (working) code but I was unable to put the same logic into a function usable with array_filter
$arr2=array();
$StartWith="1.1.1";
foreach ($arr as $k=>$v){
$sp=strpos($k, $StartWith);
if ($sp===0){
if (strlen($k)==strlen($StartWith) ||
strlen($k)>strlen($StartWith) && substr($k,strlen($StartWith),1)=='.'){
$arr2[$k]=$v;
}
}
}
Now, my questions are:
Is it a good idea/practice to use array_filter instead of the above code?
If yes please help me writing a function (I've not understood how to).
array_filter()
is not very useful here (even may happen that callback function make it heavior).
You can do it like below (faster and easier):-
$search = '1.1.1';
$final = [];
if(isset($arr[$search])){
$final[$search] = $arr[$search];
}
foreach($arr as $key=>$val){
if(count(explode('.',$search)) < count(explode('.',$key)) && array_intersect(explode('.',$search),explode('.',$key)) == explode('.',$search)){
$final[$key]= $val;
}
}
print_r($final);
Output:-https://eval.in/897183