note 99609 added to control-structures.foreach

From: Date: Thu, 26 Aug 2010 12:11:42 +0000
Subject: note 99609 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-172083@lists.php.net to get a copy of this message
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). ---- Server IP: 212.124.37.9 Probable Submitter: 77.8.156.204 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/99609 Del: integrated -- https://master.php.net/note/delete/99609/integrated Del: useless -- https://master.php.net/note/delete/99609/useless Del: bad code -- https://master.php.net/note/delete/99609/bad+code Del: spam -- https://master.php.net/note/delete/99609/spam Del: non-english -- https://master.php.net/note/delete/99609/non-english Del: in docs -- https://master.php.net/note/delete/99609/in+docs Del: other reasons-- https://master.php.net/note/delete/99609 Reject -- https://master.php.net/note/reject/99609 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172083) next »