PHP - Counting matching records in multi-dimensional array

Associate
Joined
18 Oct 2002
Posts
2,055
Location
Southend-on-Sea
Bit of a newb with PHP, I'm trying to count records in a multi-dimensional array that contain a certain string in the second column.

The code I have is:

Code:
$total = 0;
for($i = 0; $i < count($results); $i++) 
{
if($results[$i][1] == 'Settlement')
{$total = $total + 1;} 
} 
echo $total;

So basically I have an array called $results and I want to count how many records have the string Settlement in the second column of each row. However, the code above is returning zero everytime, although there are around 200 records that should match.

The array is definitely populated, I have a print loop straight after the code above that prints all records.

TBH, I'm not even sure if the code above is the correct way to go about this, so any help/advice appreciated.

Thanks
 
And just to confirm the array does contain valid data, if I use this code with one addtional line:

Code:
$total = 0;
for($i = 0; $i < count($results); $i++) 
{
[B]echo $results[$i][1];[/B]
if($results[$i][1] == 'Settlement')
{ $total = $total + 1;} 
} 
echo $total;

Then the string I expect to be shown is printed for each record, including around 200 Settlement entries.
 
Last edited:
To be honest I'm not much of a php guy but what stands out is $results[$i][1] - Is index 1 definitely what you should be using ? To check you can print_r an array which conveniently prints all elements, but it could be that none of the elements are 'Settlement' if its set up like results[3][1]: 'Settlement' -> x

Maybe I'm talking rubbish, but with any luck you will get some kind of hint out of this, as I said I'm not a php guy :)
 
With that bit of extra info in your second post it sounds like the elements of the array are being initialised at the same time you're trying to access them.. Is the array definitely fully populated before that code gets run?
 
Last edited:
To be honest I'm not much of a php guy but what stands out is $results[$i][1] - Is index 1 definitely what you should be using ? To check you can print_r an array which conveniently prints all elements, but it could be that none of the elements are 'Settlement' if its set up like results[3][1]: 'Settlement' -> x

Maybe I'm talking rubbish, but with any luck you will get some kind of hint out of this, as I said I'm not a php guy :)

Thanks for the response. Yes, pretty sure $results[1] is correct. In my second example the line:

Code:
echo $results[$i][1];

prints the string I would expect to see, including "Settlement" in the relevant entries.
 
print_r($results) gives the following:

Array ( [0] => Array
( [0] => HDC2796
[1] => Settlement
[2] => variant Object )

So index [1] is definitely the correct one.
 
Back
Top Bottom