PHP OOP: Weird Array Return - php

I have the following 'Course' class:
class Course {
// The constructor just sets the database object
public function __construct($mysqli) {
$this->mysqli = $mysqli;
}
public function getCourseInfoByID($id) {
$result = $this->mysqli->query("SELECT * FROM courses WHERE id='$id'");
$course_info = $result->fetch_array();
// If found, return the student object
if($course_info) {
return $course_info;
}
return FALSE;
}
}
When I declare the class and try to run the function "getCourseInfoByID", I get weird results (see below)
$cid = process_get_request('cid');
$course = new Course($mysqli);
if(! $course_info = $course->getCourseInfoByID($cid)) {
$error[] = "Invalid Course ID";
setError();
redirectTo("instructors.php");
}
print_r($course_info);
I get this:
Array ( [0] => 2 [id] => 2 [1] => 1 [course_type_id] => 1 [2] => 1 [instructor_id] => 1 [3] => Tooele [dz_name] => Tooele [4] => 4 Airport Road [dz_address] => 4 Airport Road [5] => Tooele [dz_city] => Tooele [6] => Utah [dz_state] => Utah [7] => 84020 [dz_zip] => 84020 [8] => [dz_email] => [9] => 2011-12-30 17:25:12 [created] => 2011-12-30 17:25:12 [10] => 2012-01-02 16:24:08 [start_date] => 2012-01-02 16:24:08 [11] => 2012-01-08 16:24:17 [end_date] => 2012-01-08 16:24:17 [12] => 10 [student_slots] => 10 [13] => Brett will also be assisting in teaching this course as Nathan's assistant. Brett paid Nathan quite well to be his assistant. [notes] => Brett will also be assisting in teaching this course as Nathan's assistant. Brett paid Nathan quite well to be his assistant. [14] => 0 [approved_by] => 0 [15] => 0000-00-00 00:00:00 [approved_on] => 0000-00-00 00:00:00 [16] => 0 [completed] => 0 )
Why is each record duplicated?

This is happening because you are returning both numeric and associative indexes. You should use fetch_assoc() or pass the appropriate constant MYSQLI_ASSOC or MYSQLI_NUM to return just those keys.
See documentation on mysqli_result::fetch_array().
As an aside I would type hint your constructor to force the passing of a mysqli class so you can't accidentally pass an invalid argument.

Read the docs for the fetch_array() method. The second parameter defaults to MYSQLI_BOTH.

Related

Array - Select the sub children id's from an array

I have this array built from a function that sorts allowed or valid url slugs and their ids into another array. I can call the current category id by passing the url slug to the category. Now I need to get the children category ids (if any) so i can call the appropriate items from the database for display purpose.
Heres an example of the array:
Array (
[radios] => 1
[radios/motorola] => 2
[radios/motorola/handheld] => 3
[radios/motorola/mobile] => 4
[radios/icom] => 5
[radios/icom/handheld] => 6
[radios/icom/mobile] => 7
[radios/mics-and-speakers] => 8
[radios/mounts] => 9
[radios/radio-other] => 10
[misc] => 11
[misc/led] => 12
[phones] => 13
[phones/samsung] => 14
[phones/lg] => 15
[phones/motorola] => 16
[phones/huawei] => 17
[phones/blackberry] => 18
[phones/flip] => 19
[boosters] => 20
[boosters/standalone] => 21
[boosters/indoor-antenna] => 22
[boosters/outdoor-antenna] => 23
[boosters/connections] => 24
[accessories] => 25
[accessories/cases] => 26
[accessories/other] => 27
[internet] => 28
[internet/fusion] => 29
[internet/point-to-point] => 30
[internet/hotspots] => 31
[internet/gateways] => 32
[internet/switches] => 33
[cameras] => 34
[cameras/complete-kits] => 35
[cameras/additional-cameras] => 36
[cameras/other] => 37
);
As you can see, each result points to the category ID of that group. If i visit the following url:
http://example.com/store/cameras
I can print out that THE PATH CURRENTLY IS: 34 which is correct. Since It has children under it, I also need their ID's and the ID's of any of their children, etc etc. That way on radios, i can show ALL of the sub category items, and on radios/motorola i am only showing the Motorola based items and its children, and such down the line.
If there an easy way, using this array I have now, to sort the children (if any) all the way down and get back just their id's (preferably in a new array) for showing database items?
You might want to create a function like this to filter your array,
function filterArray($array, $term) {
$pattern = "/\b" . str_replace($term, '/', '\/') . "\b/i";
foreach($array as $key => $value) {
if(preg_match($pattern, $key)) {
/* Following condition makes sure that your search
will match starting from the beginning. */
if (stripos(trim($key), $term) === 0){
$filtred[] = $value;
}
}
}
}
Then call the above function with the $array and your search $term.
filterArray($array, 'radios') will give you this,
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )
filterArray($array, 'radios/motorola') will give you this,
Array ( [0] => 2 [1] => 3 [2] => 4 )
And so on.. I hope this helps.
You can maybe try double layer array, so that you can store values like this,
Array (
[name] => John
[surname] => Smith
[contact] => Array (
[address] => 18 Maple Street
[number] => 555 477 77 77
)
)
This way if you need to print something from "contact" you can use a loop and print all childs of contact field.

in mysql, how do you get data based on php array with additional filters?

Say, this is my php array.
postids = Array
(
[0] => 2172
[1] => 383
[2] => 2915
[3] => 677
[4] => 1289
[5] => 1654
[6] => 2252
[7] => 2366
[8] => 2998
[9] => 2442
[10] => 1246
)
Now in mysql table (t1) looks like this.
|postid|type|switch|
|1|A|0|
|2|A|1|
|3|A|0|
...
|383|A|0|
...
|1246|A|1|
...
|2172|A|1|
...
|2442|A|0|
So, I want to select postid of type 'A' where switch = 1 and order by my php array and includes post ids from my array.
so, is there any query like
select postids from t1 where type = 'A' and switch = 1 and postids = {<?php echo postids; ?>}
How do I achieve this?
You can use logical conditions in the WHERE,
SELECT * FROM table WHERE type='A' AND switch='1'

loop through multidimensional array and order sub-array by scores

I am trying to calculate the winning order of golfers when they are tied in a competition.
These golf competitions are using the "stableford" points scoring system, where you score points per hole with the highest points winning. Compared to normal golf "stroke play" where the lowest score wins (though this also has the countback system, only calculating the lowest score in the event of a tie...)
The rules are to use a "countback". i.e., if scores are tied after 9 holes, the best placed of the ties is the best score from the last 8 holes. then 7 holes, etc.
The best I can come up with is 2 arrays.
An array with all the players who tied in a given round. ($ties)
One which has the full score data in (referencing the database playerid) for all 9 holes. ($tie_perhole)
I loop through array 1, pulling data from array 2 and using the following formula to create a temporary array with the highest score:
$max = array_keys($array,max($array));
If $max only has 1 item, this player is the highest scorer. the loop through the first array is "by reference", so on the next iteration of the loop, his playerid is now longer in the array, thus ignored. this continues until there is only 1 playerid left in the first array.
However, it only works if a single player wins in each iteration. The scenario that doesn't work is if a sub-set of players tie on any iterations / countbacks.
I think my problem is the current structure I have will need the original $ties array to become split, and then to continue to iterate through the split arrays in the same way...
As an example...
The $ties array is as follows:
Array
(
[18] => Array
(
[0] => 77
[1] => 79
[2] => 76
[3] => 78
)
)
The $tie_perhole (score data) array is as follows:
Array
(
[18] => Array
(
[77] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[79] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 14
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[76] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[78] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 13
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
)
)
So in this competition, player's 78 and 79 score highest on the 8th hole countback (17pts), so 1st and 2nd should be between them. Player 79 should then be 1st on the 6th hole countback (14pts, compared to 13pts). The same should occur for 3rd and 4th place with the 2 remaining other players.
There are other scenarios that can occur here, in that within a competition, there will likely be many groups of players (of different amounts) on different tied points through the leaderboard.
Also note, there will be some players on the leaderboard who are NOT tied and stay in their current outright position.
The basics of the working code I have is:
foreach ($ties as $comparekey => &$compareval) {
$tie_loop = 0;
for ($m = 9; $m >= 1; $m--) {
$compare = array();
foreach ($compareval as $tie) {
$compare[$tie] = $tie_perhole[$comparekey][$tie][$m];
}
$row = array_keys($compare,max($compare));
if (count($row) == 1) {
$indexties = array_search($row[0], $ties[$comparekey]);
unset($ties[$comparekey][$indexties]);
// Now update this "winners" finishing position in a sorted array
// This is a multidimensional array too, with custom function...
$indexresults = searchForId($row[0], $comp_results_arr);
$comp_results_arr[$indexresults][position] = $tie_loop;
$tie_loop++;
}
// I think I need conditions here to filter if a subset of players tie
// Other than count($row) == 1
// And possibly splitting out into multiple $ties arrays for each thread...
if (empty($ties[$comparekey])) {
break;
}
}
}
usort($comp_results_arr, 'compare_posn_asc');
foreach($comp_results_arr as $row) {
//echo an HTML table...
}
Thanks in advance for any helpful insights, tips, thoughts, etc...
Robert Cathay asked for more scenarios. So here is another...
The leaderboard actually has more entrants (player 26 had a bad round...), but the code i need help with is only bothered about the ties within the leaderboard.
Summary leaderboard:
Points Player
21 48
21 75
20 73
20 1
13 26
This example produces a $tie_perhole array of:
Array
(
[21] => Array
(
[75] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[48] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 13
[5] => 11
[4] => 9
[3] => 8
[2] => 5
[1] => 3
)
)
[20] => Array
(
[73] => Array
(
[9] => 20
[8] => 18
[7] => 16
[6] => 13
[5] => 11
[4] => 8
[3] => 6
[2] => 5
[1] => 3
)
[1] => Array
(
[9] => 20
[8] => 17
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 4
[1] => 2
)
)
)
In this example, the array shows that players 75 and 48 scored 21 points that player 75 will eventually win on the 6th hole countback (14pts compared to 13pts) and player 48 is 2nd. In the next tied group, players 73 and 1 scored 20 points, and player 73 will win this group on the 8th hole countback and finishes 3rd (18 pts compared to 17 pts), with player 1 in 4th. player 26 is then 5th.
Note, the $tie_loop is added to another array to calculate the 1st to 5th place finishing positions, so that is working.
Hopefully that is enough to help.
Ok, so I don't understand golf at all... hahaha BUT! I think I got the gist of this problem, so heres my solution.
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
* Date : Aug/04/2015
**/
$golfers = [
"A" => [1,5,9,1,1,2,3,4,9],
"B" => [2,6,4,2,4,4,1,9,3],
"C" => [3,4,9,8,1,1,5,1,3],
"D" => [1,5,1,1,1,5,4,5,8]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer=>$score ) { // Get key and value
$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)array_sum($score_sub); // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return array(end($positions), key($positions)); // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$winner = get_winners($golfers,$hole); // Get all ties, if any.
if(count($winner[0]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner[0])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Ok... Now ill explain my method...
Since we need to know the highest score and it might be ties, it makes no sense to me to maintain all that in separate arrays, instead I just reversed the
golfer => scores
to
Tota_score => golfers
That way when we can sort the array by key and obtain all the golfers with the highest score.
Now total_score is the total sum of a subset of the holes scores array. So... the first time this function runs, it will add all 9 holes, in this case theres 3 golfers that end up with the same score.
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => 35
)
Since the total count of golfers is not 1 and we are still in the 9th hole, we run this again, but this time only against those 3 golfers and the current hole - 1, so we are only adding up to the 8th hole this time.
Array
(
[0] => Array
(
[0] => B
[1] => C
)
[1] => 32
)
We had another tie.... this process will continue until we reach the final hole, or a winner.
Array
(
[0] => Array
(
[0] => C
)
[1] => 31
)
EDIT
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
**/
$golfers = [
"77" => [2,4,6,8,10,12,14,16,18],
"79" => [3,5,7,9,11,14,15,17,18],
"76" => [2,4,6,8,10,12,14,16,18],
"78" => [3,5,7,9,11,13,15,17,18]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer => $score) { // Get key and value
//$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)$score[$hole-1]; // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return [
"winner"=> end($positions),
"score" => key($positions),
"tiebreaker_hole" => [
"hole"=>$hole,
"score"=> key($positions)],
]; // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$highest = get_winners($golfers,$hole); // Get all ties, if any.
$winner = $highest;
if(count($winner["winner"]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner["winner"])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
$winner["score"] = $highest["score"];
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Result:
Array
(
[winner] => Array
(
[0] => 79
)
[score] => 18
[tiebreaker_hole] => Array
(
[hole] => 6
[score] => 14
)
)

How to filter tag/product_collection resource model by tag name in magento

i want to filter tag/product_collection resource model by tag name.
for that i have written below's code
$collection = Mage::getResourceModel('tag/product_collection');
$collection->addFieldToFilter("name",array('like'=>'%dixit%'));
print_r($collection->getData());
Then it shows just null array.
if i will comment
$collection->addFieldToFilter("name",array('like'=>'%dixit%'));
this line then its shows below's output
Array ( [0] => Array ( [entity_id] => 323 [entity_type_id] => 4 [attribute_set_id] => 4 [type_id] => simple [sku] => 8018-90 [has_options] => 0 [required_options] => 0 [created_at] => 2010-03-11 12:17:46 [updated_at] => 2013-07-24 12:12:56 [product_id] => 323 [item_store_id] => 1 [tag_id] => 1 [name] => dixit [tag_status] => 0 [tag_name] => dixit ) )
So how to filter using like query this model.
i have try both filter attribute way
$collection->addFieldToFilter("name",array('like'=>'%dixit%'));
$collection->addAttributeToFilter("name",array('like'=>'%dixit%'));
But none of them working.
$collection->getSelect()->Where(' name like ?',"% dixit %");
Using this way you can filter tag_name as requirement.
getSelect() method get select query and we just append where query to select query using where methods.
its simple method.
i have check its working fine.
Hello check below code may be help you
$tagName='dixit';
$tagId= Mage::getModel('tag/tag')->loadByName($tagName)->getId();
$tagId = 3;
$products = Mage::getResourceModel('tag/product_collection')
->addAttributeToSelect('sku')
->addAttributeToSelect('name')
->addTagFilter($tagId);
print_r($products->getData());

How to check is timezone identifier valid from code?

I'll try to explain what's the problem here.
According to list of supported timezones from PHP manual, I can see all valid TZ identifiers in PHP.
My first question is how to get that list from code but that's not what I really need.
My final goal is to write function isValidTimezoneId() that returns TRUE if timezone is valid, otherwise it should return FALSE.
function isValidTimezoneId($timezoneId) {
# ...function body...
return ?; # TRUE or FALSE
}
So, when I pass TZ identifier using $timezoneId (string) in function I need boolean result.
Well, what I have so far...
1) Solution using # operator
First solution I've got is something like this:
function isValidTimezoneId($timezoneId) {
$savedZone = date_default_timezone_get(); # save current zone
$res = $savedZone == $timezoneId; # it's TRUE if param matches current zone
if (!$res) { # 0r...
#date_default_timezone_set($timezoneId); # try to set new timezone
$res = date_default_timezone_get() == $timezoneId; # it's true if new timezone set matches param string.
}
date_default_timezone_set($savedZone); # restore back old timezone
return $res; # set result
}
That works perfectly, but I want another solution (to avoid trying to set wrong timezone)
2) Solution using timezone_identifiers_list()
Then, I was trying to get list of valid timezone identifiers and check it against parameter using in_array() function. So I've tried to use timezone_identifiers_list(), but that was not so good because a lot of timezones was missing in array returned by this function (alias of DateTimeZone::listIdentifiers()). At first sight that was exactly what I was looking for.
function isValidTimezoneId($timezoneId) {
$zoneList = timezone_identifiers_list(); # list of (all) valid timezones
return in_array($timezoneId, $zoneList); # set result
}
This code looks nice and easy but than I've found that $zoneList array contains ~400 elements. According to my calculations it should return 550+ elements. 150+ elements are missing... So that's not good enough as solution for my problem.
3) Solution based on DateTimeZone::listAbbreviations()
This is last step on my way trying to find perfect solution. Using array returned by this method I can extract all timezone identifiers supported by PHP.
function createTZlist() {
$tza = DateTimeZone::listAbbreviations();
$tzlist = array();
foreach ($tza as $zone)
foreach ($zone as $item)
if (is_string($item['timezone_id']) && $item['timezone_id'] != '')
$tzlist[] = $item['timezone_id'];
$tzlist = array_unique($tzlist);
asort($tzlist);
return array_values($tzlist);
}
This function returns 563 elements (in Example #2 I've got just 407).
I've tried to find differences between those two arrays:
$a1 = timezone_identifiers_list();
$a2 = createTZlist();
print_r(array_values(array_diff($a2, $a1)));
Result is:
Array
(
[0] => Africa/Asmera
[1] => Africa/Timbuktu
[2] => America/Argentina/ComodRivadavia
[3] => America/Atka
[4] => America/Buenos_Aires
[5] => America/Catamarca
[6] => America/Coral_Harbour
[7] => America/Cordoba
[8] => America/Ensenada
[9] => America/Fort_Wayne
[10] => America/Indianapolis
[11] => America/Jujuy
[12] => America/Knox_IN
[13] => America/Louisville
[14] => America/Mendoza
[15] => America/Porto_Acre
[16] => America/Rosario
[17] => America/Virgin
[18] => Asia/Ashkhabad
[19] => Asia/Calcutta
[20] => Asia/Chungking
[21] => Asia/Dacca
[22] => Asia/Istanbul
[23] => Asia/Katmandu
[24] => Asia/Macao
[25] => Asia/Saigon
[26] => Asia/Tel_Aviv
[27] => Asia/Thimbu
[28] => Asia/Ujung_Pandang
[29] => Asia/Ulan_Bator
[30] => Atlantic/Faeroe
[31] => Atlantic/Jan_Mayen
[32] => Australia/ACT
[33] => Australia/Canberra
[34] => Australia/LHI
[35] => Australia/NSW
[36] => Australia/North
[37] => Australia/Queensland
[38] => Australia/South
[39] => Australia/Tasmania
[40] => Australia/Victoria
[41] => Australia/West
[42] => Australia/Yancowinna
[43] => Brazil/Acre
[44] => Brazil/DeNoronha
[45] => Brazil/East
[46] => Brazil/West
[47] => CET
[48] => CST6CDT
[49] => Canada/Atlantic
[50] => Canada/Central
[51] => Canada/East-Saskatchewan
[52] => Canada/Eastern
[53] => Canada/Mountain
[54] => Canada/Newfoundland
[55] => Canada/Pacific
[56] => Canada/Saskatchewan
[57] => Canada/Yukon
[58] => Chile/Continental
[59] => Chile/EasterIsland
[60] => Cuba
[61] => EET
[62] => EST
[63] => EST5EDT
[64] => Egypt
[65] => Eire
[66] => Etc/GMT
[67] => Etc/GMT+0
[68] => Etc/GMT+1
[69] => Etc/GMT+10
[70] => Etc/GMT+11
[71] => Etc/GMT+12
[72] => Etc/GMT+2
[73] => Etc/GMT+3
[74] => Etc/GMT+4
[75] => Etc/GMT+5
[76] => Etc/GMT+6
[77] => Etc/GMT+7
[78] => Etc/GMT+8
[79] => Etc/GMT+9
[80] => Etc/GMT-0
[81] => Etc/GMT-1
[82] => Etc/GMT-10
[83] => Etc/GMT-11
[84] => Etc/GMT-12
[85] => Etc/GMT-13
[86] => Etc/GMT-14
[87] => Etc/GMT-2
[88] => Etc/GMT-3
[89] => Etc/GMT-4
[90] => Etc/GMT-5
[91] => Etc/GMT-6
[92] => Etc/GMT-7
[93] => Etc/GMT-8
[94] => Etc/GMT-9
[95] => Etc/GMT0
[96] => Etc/Greenwich
[97] => Etc/UCT
[98] => Etc/UTC
[99] => Etc/Universal
[100] => Etc/Zulu
[101] => Europe/Belfast
[102] => Europe/Nicosia
[103] => Europe/Tiraspol
[104] => Factory
[105] => GB
[106] => GB-Eire
[107] => GMT
[108] => GMT+0
[109] => GMT-0
[110] => GMT0
[111] => Greenwich
[112] => HST
[113] => Hongkong
[114] => Iceland
[115] => Iran
[116] => Israel
[117] => Jamaica
[118] => Japan
[119] => Kwajalein
[120] => Libya
[121] => MET
[122] => MST
[123] => MST7MDT
[124] => Mexico/BajaNorte
[125] => Mexico/BajaSur
[126] => Mexico/General
[127] => NZ
[128] => NZ-CHAT
[129] => Navajo
[130] => PRC
[131] => PST8PDT
[132] => Pacific/Ponape
[133] => Pacific/Samoa
[134] => Pacific/Truk
[135] => Pacific/Yap
[136] => Poland
[137] => Portugal
[138] => ROC
[139] => ROK
[140] => Singapore
[141] => Turkey
[142] => UCT
[143] => US/Alaska
[144] => US/Aleutian
[145] => US/Arizona
[146] => US/Central
[147] => US/East-Indiana
[148] => US/Eastern
[149] => US/Hawaii
[150] => US/Indiana-Starke
[151] => US/Michigan
[152] => US/Mountain
[153] => US/Pacific
[154] => US/Pacific-New
[155] => US/Samoa
[156] => Universal
[157] => W-SU
[158] => WET
[159] => Zulu
)
This list contains all valid TZ identifiers that Example #2 failed to match.
There's four TZ identifiers more (part of $a1):
print_r(array_values(array_diff($a1, $a2)));
Output
Array
(
[0] => America/Bahia_Banderas
[1] => Antarctica/Macquarie
[2] => Pacific/Chuuk
[3] => Pacific/Pohnpei
)
So now, I have almost perfect solution...
function isValidTimezoneId($timezoneId) {
$zoneList = createTZlist(); # list of all valid timezones (last 4 are not included)
return in_array($timezoneId, $zoneList); # set result
}
That's my solution and I can use it. Of course, I use this function as part of class so I don't need to generate $zoneList on every methods call.
What I really need here?
I'm wondering, is there any easier (quicker) solution to get list of all valid timezone identifiers as array (I want to avoid extracting that list from DateTimeZone::listAbbreviations() if that's possible)? Or if you know another way how to check is timezone parameter valid, please let me know (I repeat, # operator can't be part of solution).
P.S. If you need more details and examples, let me know. I guess you don't.
I'm using PHP 5.3.5 (think that's not important).
Update
Any part of code that throws exception on invalid timezone string (hidden using # or caught using try..catch block) is not solution I'm looking for.
Another update
I've put small bounty on this question!
Now I'm looking for the easiest way how to extract list of all timezone identifiers in PHP array.
Why not use # operator?
This code works pretty well, and you don't change default timezone:
function isValidTimezoneId($timezoneId) {
#$tz=timezone_open($timezoneId);
return $tz!==FALSE;
}
If you don't want #, you can do:
function isValidTimezoneId($timezoneId) {
try{
new DateTimeZone($timezoneId);
}catch(Exception $e){
return FALSE;
}
return TRUE;
}
You solution works fine, so if it's speed you're looking for I would look more closely at what you're doing with your arrays. I've timed a few thousand trials to get reasonable average times, and these are the results:
createTZlist : 20,713 microseconds per run
createTZlist2 : 13,848 microseconds per run
Here's the faster function:
function createTZList2()
{
$out = array();
$tza = timezone_abbreviations_list();
foreach ($tza as $zone)
{
foreach ($zone as $item)
{
$out[$item['timezone_id']] = 1;
}
}
unset($out['']);
ksort($out);
return array_keys($out);
}
The if test is faster if you reduce it to just if ($item['timezone_id']), but rather than running it 489 times to catch a single case, it's quicker to unset the empty key afterwards.
Setting hash keys allows us the skip the array_unique() call which is more expensive. Sorting the keys and then extracting them is a tiny bit faster than extracting them and then sorting the extracted list.
If you drop the sorting (which is not needed unless you're comparing the list), it gets down to 12,339 microseconds.
But really, you don't need to return the keys anyway. Looking at the holistic isValidTimezoneId(), you'd be better off doing this:
function isValidTimezoneId2($tzid)
{
$valid = array();
$tza = timezone_abbreviations_list();
foreach ($tza as $zone)
{
foreach ($zone as $item)
{
$valid[$item['timezone_id']] = true;
}
}
unset($valid['']);
return !!$valid[$tzid];
}
That is, assuming you only need to test once per execution, otherwise you'd want to save $valid after the first run. This approach avoids having to do a sort or converting the keys to values, key lookups are faster than in_array() searches and there's no extra function call. Setting the array values to true instead of 1 also removes a single cast when the result is true.
This brings it reliably down to under 12ms on my test machine, almost half the time of your example. A fun experiment in micro-optimizations!
When I tried this on a Linux system running 5.3.6, your Example #2 gave me 411 zones and Example #3 gave 496. The following slight modification to Example #2 gives me 591:
$zoneList = timezone_identifiers_list(DateTimeZone::ALL_WITH_BC);
There are no zones returned by Example #3 that are not returned with that modified Example #2.
On an OS X system running 5.3.3, Example #2 gives 407, Example #3 gives 564, and the modified Example #2 gives 565. Again, there are no zones returned by Example #3 that are not returned with that modified Example #2.
On a Linux system running 5.2.6 with the timezonedb PECL extension installed, Example #2 gives me 571 zones and Example #3 gives me only 488. There are no zones returned by Example #3 that are not by Example #2 on this system. The constant DateTimeZone::ALL_WITH_BC does not seem to exist in 5.2.6; it was probably added in 5.3.0.
So it seems the simplest way to get a list of all time zones in 5.3.x is
timezone_identifiers_list(DateTimeZone::ALL_WITH_BC), and in 5.2.x is timezone_identifiers_list(). The simplest (if not fastest) way to check if a particular string is a valid time zone is still probably #timezone_open($timezoneId) !== false.
If you're on Linux most if not all information on timezones there stored at /usr/share/zoneinfo/. You can walk over them using is_file() and related functions.
You can also parse the former files with zdump for codes or fetch sources for these files and grep/cut out needed info. Again, you are not obliged to use built-in functions to accomplish the task. There isn't a rationale why would someone force you to use only the built-in date functions.
See in PHP sources on php_date.c and timezonemap.h that`s why I can say this is always in 101.111111% static info (but per php build).
If you want to get it dynamically, use timezone_abbreviations_list as DateTimeZone::listAbbreviations is a map to it.
As you can see all these values are just one time filled list for current PHP version.
So much faster solution is simple -- prepare somehow static file with retrieved ids one time per server during install of your app and use it.
For example:
function isValidTZ($zone) {
static $zones = null;
if (null === $zones) {
include $YOUR_APP_STORAGE . '/tz_list.php';
}
// isset is muuuch faster than array_key_exists and also than in_array
// so you should work with structure like [key => 1]
return isset($zones[$zone]);
}
tz_list.php should be like this:
<?php
$zones = array(
'Africa/Abidjan' => 1,
'Africa/Accra' => 1,
'Africa/Addis_Ababa' => 1,
// ...
);
I would research what changes the perfect array and use a basic caching mechanism (like store the array in a file, that you include and update when needed). You're currently optimizing building an array that is static for 99.9999% of all the requests.
Edit:
Ok, static/dynamic.
if( !function_exists(timezone_version_get) )
{
function timezone_version_get() { return '2009.6'; }
}
include 'tz_list_' . PHP_VERSION . '_' . timezone_version_get() . '.php';
Now each time the php version is updated, the file should be regenerated automatically by your code.
In case of php<5.3, how about this?
public static function is_valid_timezone($timezone)
{
$now_timezone = #date_default_timezone_get();
$result = #date_default_timezone_set($timezone);
if( $now_timezone ){
// set back to current timezone
date_default_timezone_set($now_timezone);
}
return $result;
}
Just an addendum to Cal's excellent answer. I think the following might be even faster...
function isValidTimezoneID($tzid) {
if (empty($tzid)) {
return false;
}
foreach (timezone_abbreviations_list() as $zone) {
foreach ($zone as $item) {
if ($item["timezone_id"] == $tzid) {
return true;
}
}
}
return false;
}

Categories