I have two arrays (records returned from a database query) that I'm merging. I then need to get a count of the elements in the combined array.
Here are the print_r results of the two original arrays:
Array(
[0] => stdClass Object([id] => 25590)
[1] => stdClass Object([id] => 40657)
[2] => stdClass Object([id] => 60685)
[3] => stdClass Object([id] => 61900)
[4] => stdClass Object([id] => 65224)
)
Array(
[0] => stdClass Object([id] => 88406)
)
Merged array created like this:
$licensed_users = array_unique(array_merge($lu, $lu2));
And the results of the merge (in this case there weren't any duplicates, but there could be, hence the array_unique)
Array(
[0] => stdClass Object([id] => 25590)
[1] => stdClass Object([id] => 40657)
[2] => stdClass Object([id] => 60685)
[3] => stdClass Object([id] => 61900)
[4] => stdClass Object([id] => 65224)
[5] => stdClass Object([id] => 88406)
)
The array is assigned to a session variable, to be used on another page:
$_SESSION['licensed_users'] = $licensed_users;
I now want to know how many elements are in the merged array via the session variable.
count($_SESSION['licensed_users'])
I would expect this to return 6. Instead, it returns 1. Any idea why?
EDITED TO ADD CODE FOR @SURREALDREAMS
$_SESSION['licensed_users'] = array_unique(array_merge($lu, $lu2));
print_r($lu);
print_r($lu2);
print_r($_SESSION['licensed_users']);
echo "there are ". count($_SESSION['licensed_users']) . " licensed users";
This code returns the following:
$lu Array(
[0] => stdClass Object([id] => 25590)
[1] => stdClass Object([id] => 40657)
[2] => stdClass Object([id] => 60685)
[3] => stdClass Object([id] => 61900)
[4] => stdClass Object([id] => 65224)
)
$lu2 Array(
[0] => stdClass Object([id] => 88406)
)
$_SESSION['licensed_users'] Array(
[0] => stdClass Object([id] => 25590)
)
The echo line returns 1.
If I try it the other way you suggested:
$licensed_users = array_unique(array_merge($lu, $lu2));
$_SESSION['licensed_users'] = $licensed_users;
echo "there are ". count($_SESSION['licensed_users'], COUNT_RECURSIVE) -1 . " licensed users";
the arrays returned have the same contents, but the echo line returns -1.
It's counting the contents of $_SESSION['licensed_users'], which is 1 - your $licensed_users array. You could instead try:
count($_SESSION['licensed_users'], COUNT_RECURSIVE);
This will return 7. You could approach this knowing your structure and use:
count($_SESSION['licensed_users'], COUNT_RECURSIVE) -1;
Which returns the expected 6.
To simplify a bit more, consider this:
$_SESSION['licensed_users'] = array_unique(array_merge($lu, $lu2));
Then count($_SESSION['licensed_users']; should return 6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With