I am a novice in PHP. I want return an array from a function in one php file and access the elements of array in another php file.
Issue I am facing is when I run the source file and print elements of array then I was able to see all tags in console but when I return the array and print it in another php file then only one item is returned or no items are returned.
source file.php
<?php
// Load the Google API PHP Client Library.
require_once 'C:/xxxx/google-api-php-client-2.2.4/vendor/autoload.php';
function getTags(){
$KEY_FILE_LOCATION = 'C:/xxx/service-account-credentials.json';
$params=array(
'dimensions' => 'ga:dimension5,ga:dimension2',
'filters' => 'ga:dimension5==123456'
);
$results = $analytics->data_ga->get(
'ga:' . 123456,
'2019-08-29',
'yesterday',
'ga:sessions',
$params
);
$rows = $results->getRows();
$StoreTags = array();
for($i=0;$i<sizeof($rows);$i++){
$ExtractTag_arr = explode(',',$rows[$i][1]);
for($j=0;$j<count($ExtractTag_arr);$j++){
$StoreTags[]=$ExtractTag_arr[$j];
}
$ExtractTag_arr='';
}
$unique_tags = array_unique($StoreTags);
$Unique_tags_Values = array_values(array_filter($unique_tags));
$Count_UniqueTags = count($Unique_tags_Values);
$Count_StoreTags=count($StoreTags);
for($a=0;$a<$Count_UniqueTags;$a++){
$Count_Occurances = 0;
$UniqueTags_Value = $Unique_tags_Values[$a];
for ($k=0;$k<$Count_StoreTags;$k++){
if ($UniqueTags_Value == $StoreTags[$k]){
$Count_Occurances = $Count_Occurances+1;
}
else{
$Count_Occurances = $Count_Occurances+0;
}
}
$Display_Tags=array($Unique_tags_Values[$a], $Count_Occurances);
return $Display_Tags;
}
}
Target file:
<?php
include 'Source.php';
get_tags = getTags();
Print_r(getTags());
When I run the target.php returns nothing and if I run source.php without return statement and can print all items in $Display_Tags
1.get_tags = getTags();
is incorrect, needs to be $get_tags = getTags();
.
2.Print_r(getTags());
needs to be print_r(getTags());
3.To overcome your issue put return $Display_Tags;
outside of the for()
loop in your function getTags()
.
<?php
include 'Source.php';
$get_tags = getTags();
print_r($get_tags);