note 99609 deleted from control-structures.foreach by googleguy

From: Date: Wed, 14 Nov 2012 22:25:00 +0000
Subject: note 99609 deleted from control-structures.foreach by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191954@lists.php.net to get a copy of this message
Note Submitter: j dot vd dot merwe at enovision dot net ---- A sample how to go through a list of array elements that resulted from mysql recordset. In this sample it checks if a file exists and removes the row from the array if it not. <?php $db->set_query("select * from documents where document_in_user = 0"); //1 $documents = $db->result_to_array($db->get_result()); //1 foreach ($documents as $key => $row) { //2 $file = "uploads/".rawurldecode($row['document_name']); if ( file_exists ( $file ) == FALSE ) { unset($documents[$key]); //3 } } $documents = array_values($documents); // reindex the array (4) ?> variables: mysql table = documents, array = $documents array key (index) = $key array row (record sort of speak) = $row explanation: 1. it gets the array from the table (mysql) 2. foreach goes through the array $documents 3. unset if record does not exist (remove the row) 4. the array_values($documents) reindexes the $documents array, for otherwise you might end up in trouble when your process will start expecting an array starting with key ($key) 0 (zero).

« previous php.notes (#191954) next »