• Notice regarding image hosts and attachments. See here.

PHP array counting

Soldato
Joined
22 Aug 2005
Posts
9,289
Location
Clydebank
If I have this code:
PHP:
$querystringNEW = 'SELECT BLAH BAH NEW';
$querystringOLD = 'SELECT BLAH OLD';
$querystringDUP = 'SELECT BLAH DUP';



$z = array( 'new' => $querystringNEW,
			'old' => $querystringOLD,
			'dup' => $querystringDUP
			);

How can I count iterate through it to extract both the 'new' and the $querystring part?

count(z$) gives me 1? So if I do a while $item <= count(z$) it obviously doesn't run. I'd expect count($z) to give me 3 ....???
 
Hum, using the count function gives me 3. As for looping:

PHP:
$querystringNEW = 'SELECT BLAH BAH NEW';
$querystringOLD = 'SELECT BLAH OLD';
$querystringDUP = 'SELECT BLAH DUP';



$z = array( 'new' => $querystringNEW,
            'old' => $querystringOLD,
            'dup' => $querystringDUP
            );  
            
print "count = " . count($z,0) . "<br /><br />";


foreach ($z as $a=>$value) {
    print "$a = $value<br />";
}
 
Thanks!

Very helpful

I realised he problem DOH!

in between declaring the array and echo the count (echo vs print? ), I had this code
as a little test thing ...
PHP:
foreach ($z as $z) {
    echo "Do you like $z?<P>";
}

Which I see now was asigning only 1 value to $z and hence count($z) gave me answer of 1.

:)
 
More array woes :(

I now have a 2d array, basically holding old/new, querystring for multiple dates:

PHP:
	$querystring = array( $tablename => array( 'New' => $querystringNEW,
											'Old' => $querystringOLD
											)
					);

This gets added to and print_r gives this:

Code:
Array ( [ts1239836400] => Array ( [New] => SELECT * FROM ts1239836400_NEW ORDER BY id DESC [Old] => SELECT * FROM ts1239836400_OLD ORDER BY id DESC ) )

How can I loop through and extract each value i.e. (ts1239836400, New, 'SELECT * FROM ts1239836400_NEW ORDER BY id DESC') for the first result, which I then wil pass to a drawTable function.?

i tried
PHP:
foreach ($querystring as $timestamp=>$type=>$query) {
    print "$timestamp = $type = $query<br />";
}

But that doesn't seem to work?

Also my googling has brought up only numerically indexed arrays which can be extracted with a counter loop...

Any ideas? Cheers
 
this does the trick

PHP:
foreach($querystring as $date=>$app_type)
{
	
	foreach($app_type as $app=>$query)
	{
		echo '1' . substr($date, 2) .'<P>';
		echo '2' .$app . '<P>5' . $query .'<P>';
		echo '<hr>';
		 	 drawTable((substr($date, 2)), $app, $query);
	}
}
 
Yep, you need to use a pair of nested foreach loops to to access elements in a 2D array (array of arrays) when you don't know the position of elements.

PHP:
$matrix = array(array(0, 1, 2),
				array(3, 4, 5),
				array(6, 7, 8,));
					
foreach($matrix as $row) 
    foreach($row as $elt) 
		echo $elt;

Output: 012345678
 
Last edited:
Back
Top Bottom