Skip to main content

Posts

Showing posts from November, 2013

Quickly cast array elements in PHP

It's not immediately obvious, but there is a concise way to cast all elements of an array to a single type.  It's all possible with the array_walk() function. array_walk($test, function(&$value, $key){$value = (integer) $value;}); Used in an example it would look like this. $sampleArray = array("one"=>"1", "two"=>"2", "three"=>3, "four"=>"4d"); var_dump($sampleArray); array_walk($sampleArray, function(&$value, $key){$value = (integer) $value;}); //--------------------------------^ Required! ^ //--------------------------------------------------------+ Type to cast to. var_dump($sampleArray); NOTE:  It's important to note that the ampersand is necessary.  See the note about references on the second argument of the array_walk() function documentation.

Consolidated query executions version 2

This is an extension of a piece from late last year titled, " Consolidated query executions ."  That version had a problem in that it didn't work as advertised with MySQL .  As a result it has been re-worked and listed here.  It's pending further testing, specifically against SQL Server , it's just listed now in the event that it may prove useful to someone. private function run($sql) { $Query = $this->Conn->prepare($sql); if((func_num_args() == 2) && is_array(func_get_arg(1))) { $Query->execute(func_get_arg(1)); } else { $Query->execute(array()); } $errorInfo = $Query->errorInfo(); if($errorInfo[1] != NULL) { return $errorInfo[2]; } $rowCount = $Query->rowCount(); $rowCountStatus = $Query->errorCode(); $fetch = $Query->fetchAll(\PDO::FETCH_ASSOC); $fetchStatus = $Query->errorCode(); if(($rowCountStatus == "00000") && ($fetchStatus == "00000")) { return $fetch; } els