Tips – PHP Reference Book Blog https://phpreferencebook.com/ PHP Reference: Beginner to Intermediate PHP5 Sun, 01 Oct 2017 17:21:19 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.13 Search Speed: Isset vs In_array vs MySQL Query https://phpreferencebook.com/tips/isset-in_array-mysql/ https://phpreferencebook.com/tips/isset-in_array-mysql/#comments Thu, 18 Aug 2011 03:07:33 +0000 https://phpreferencebook.com/?p=445 Continue reading Search Speed: Isset vs In_array vs MySQL Query]]> As databases and visitors grow, sometimes ‘old code’ doesn’t work like it use to: it takes too long or times out for exceeding the maximum time allowed by your server for PHP execution. On a MySQL table with 30,000 rows (not too many), the query was checking one column for <3 and then matching a long list (10,000) of values in a second column using a long WHERE column2=’value’ clause. Here is an example of the table:

|--column1--|--column2--|
|     0     |    1234   |
|     3     |    5678   |
-------------------------

A MySQL query took a while, but didn’t time out when the list of WHERE column2=’value’ was less than 7000, but it was just overwhelmed at 10,000. Okay, fine, time to go to phase two: in_array().
There was an existing array of values for column2, so I could simply pull a list of <3 from MySQL (quick) and then loop through (foreach) each of the results and check whether they are in_array() for the original source. If they were, just save them to a brand new array that I’ll use to work further through the problem. For clarification, that means that the system should go through 10,000+ iterations and check if each value is in_array(). If you had not already guessed, this was disastrous. In_Array() is very inefficient, and if you are dealing with an array that is more than 100 or so values, you’ll quickly learn this fact. So what to do? Use isset().
Isset(), as a function, is incredibly fast. It only checks whether something exists, and is a great way to check for whether something exists in an array. However, the trick is using isset() will look at the KEYS, while in_array() will look at the VALUES. Is that problem? Not if you build the original array as [value]=>value (set the KEY and VALUE the same). Now, as long as your values are valid keys and unique, this won’t be a problem. Then, you can use a foreach loop to check whether it is found in the original array. Here is some sample code:

$array_source = array('abc'=>'abc','def'=>'def','ghi'=>'ghi');
$array_results = array('xyz','ghi');
foreach ($array_results as $v){
  if (isset($array_source[$v])){ //fast
    $result[] = $v; //if found, save it to a fresh array
  }
}

What was the final result? The query, run 6 different times for 6 different data sets, went from a total execution time exceeding 2 minutes (MySQL), to not working at all (in_array), to 0.18 seconds. Yes, less than one second! That is the power for checking whether a value is set when comparing arrays. Isset() is even faster by a notable amount when compared to array_diff().

]]>
https://phpreferencebook.com/tips/isset-in_array-mysql/feed/ 2
MySQL Update Multiple Columns Query https://phpreferencebook.com/tips/mysql-update-multiple-columns-query/ Fri, 17 Jun 2011 21:19:57 +0000 https://phpreferencebook.com/?p=432 While the book only includes a single example on page 117 for the MySQL UPDATE query, it should have also included an example of a multiple column UPDATE. Here is an example:

UPDATE table SET column1=’newvalue’,column2=’nextvalue’ WHERE column3=’value’

]]>
Check for Common Mistakes in PHP Code https://phpreferencebook.com/tips/check-for-common-mistakes-in-php-code/ Mon, 11 Apr 2011 04:19:44 +0000 https://phpreferencebook.com/?p=415 Continue reading Check for Common Mistakes in PHP Code]]> frustrated manA while ago I posted an article on the 10 common PHP errors and mistakes. While this helped decipher some of the cryptic errors you get from PHP when executing your code, it doesn’t help you when the mistakes either are not caught by the PHP compiler ($variable == ‘hello world’; anyone?), or are tricky to track down. Well, I finally got some spare time and decided to build something for that.

It is still a work in progress, but the new PHP Code Checker will not execute your code, simply scan it as a string and run a battery of tests to find these mistakes. It is only a few weeks and less than 10 hours of work in it so far, but it is already at version 0.2 and is ready to help you. There is more coming soon, so keep tabs on the site and I hope it helps you deal with those tough code problems!

Photo courtesy of Zach Klein

]]>
MySQL Find Fields in Table not Found in First Table https://phpreferencebook.com/tips/mysql-query-not-in-exclusion-table/ Fri, 01 Jan 2010 17:49:28 +0000 https://phpreferencebook.com/?p=358 Continue reading MySQL Find Fields in Table not Found in First Table]]> It took a ton of googling, and it was really hard to find the answer. I had two tables, and wanted to do a MySQL Query that seems like a NOT IN between two tables. There are two tables with one unique field that is the same between the tables. The goal is to find the rows in the second table that are not found in the first table based upon the similar field.

I could attempt to explain this, but someone has already done a very good job of this, so I’d rather just provide a link to their content. The post is from the author of “High Performance MySQL”, Baron Schwartz, and covers writing an SQL Exclusion Join. The key area of interest is the section on LEFT OUTER joins. He offers this example query:

SELECT apples.Variety
FROM apples
    LEFT OUTER JOIN oranges
        ON apples.Price = oranges.Price
WHERE oranges.Price IS NULL

When in doubt, find someone smarter to answer the question for you. 🙂 Thanks Baron!

]]>
Quick Tip: getcwd() for Contents of Current Directory https://phpreferencebook.com/tips/getcwd-scandir-get-display-contents-current-directory/ Tue, 22 Dec 2009 14:00:52 +0000 https://phpreferencebook.com/?p=352 Continue reading Quick Tip: getcwd() for Contents of Current Directory]]> The getcwd() function is short for ‘GET Current Working Directory’. This can easily be combined with the scandir() function which returns an array of all the files and directories inside the specified directory. This tip was excluded from the book as an oversight.
 
A quick way to get a list of all the contents of the current directory is to use the following code:

function preprint($arr){
  echo '< pre>'.print_r($arr).'< /pre>';
}
$array = scandir(getcwd());
preprint($array); // nicely formatted display of the array

 
Of course, you can skip the print/echo portion if you don’t wish to display the contents and just use the array to perform other checks, but you get the idea.

]]>
Fixing strtotime -1 month https://phpreferencebook.com/tips/fixing-strtotime-1-month/ https://phpreferencebook.com/tips/fixing-strtotime-1-month/#comments Sun, 01 Nov 2009 18:03:26 +0000 https://phpreferencebook.com/?p=325 Continue reading Fixing strtotime -1 month]]> There is a bug for strtotime() when you are on the last day of a month that has 31 days in it. The function, strotime(‘-1 month’) will return the beginning of the current month, or put another way, 30 days prior. Needless to say, this is annoying. However, it doesn’t come up very often, and there is a way to fix things: by rolling back the clock 3 extra days. I ran into this problem on a different personal project, and wrote the following function to address the issue. Whenever using strtotime() and negative months, switch in strtotimefix() instead:

function strtotimefix($val,$timestamp=0){
	if ($timestamp==0){ $timestamp = time(); }
	if (date('m') == date('m',strtotime('-1 month'))){
		$timestamp = strtotime('-3 days',$timestamp);
	}else{
		if($timestamp==0){$timestamp = time();}
	}
	$strtotime = strtotime($val,$timestamp);
	return $strtotime;
}

So what’s happening? Basically, the function will check if the numeric month is the same between the current month and the month through ‘-1 month’. If so, it subtracts 3 days from the current timestamp, then runs through the strtotime function using the new timestamp. If everything is fine, nothing is altered, so you don’t have to worry that using the strtotimefix() function will break a perfectly normal strtotime(‘-1 month’) call. Be advised that if you are not doing a call with ‘-x month’, the function will return an incorrect timestamp by 3 days (I hope to update it to be self-aware and only ‘fix’ when the bug would be introduced).

Updated on March 30, 2010:
Changed it to -3 days to deal with February/March.

]]>
https://phpreferencebook.com/tips/fixing-strtotime-1-month/feed/ 3
Common Regular Expressions https://phpreferencebook.com/tips/common-regular-expressions/ https://phpreferencebook.com/tips/common-regular-expressions/#comments Sat, 18 Jul 2009 05:38:13 +0000 https://phpreferencebook.com/?p=278 Continue reading Common Regular Expressions]]> I’ve gotten better and more comfortable with regular expressions as time has passed, and sometimes I spend timing wading through google for some common regular expressions I want to put into use, because I’m sure someone has already created it. Well, this isn’t always true (or easy to find), so I decided to collect some common Regular Expressions that may benefit readers. It’s a good idea to keep two things handy if you want to play with Regular Expressions yourself:

Common Regular Expressions:

Date and Time RegEx

Time format (no seconds):
HH:MM am/pm

^([1-9]|1[012]):(0[0-9]|[1-5][0-9])\s?(am|AM|pm|PM)$

Date in mm/dd/yyyy format, with an option for m/d/yyyy (exclude zero’s)

^(0?[1-9]|1[012])[ \/.-](0?[1-9]|[12][0-9]|3[01])[ \/.-](19|20)\d\d$

Date in dd/mm/yyyy format, with an option for d/m/yyyy (exclude zero’s)

^(0?[1-9]|[12][0-9]|3[01])[ \/.-](0?[1-9]|1[012])[ \/.-](19|20)\d\d$

Demographics RegEx

Age in years – max 122

^([0-9]|[1-9][0-9]|[1-9][0-1][0-9]|[1-9]2[0-2])$

Height in Feet and Inches:
6’3″

^([1-8]')?\s?([1-9]|1[01])$

Contact Information RegEx

U.S. Phone Number – parenthesis, periods, dashes, underscore, and spaces are allowed:
(123)456-7890
(123) 456 – 7890
( 123 )456-7890
1234567890
123.456.7890
123-456-7890
123 456 7890

^[\(\s\._-]*\d{3}[\)\s\._-]*\d{3}[\s\._-]*\d{4}$

U.S. Zip Code – 5 or 9 digit with dash

^\d{5}([\-]\d{4}){0,1}$

Email Address – (use preg_match) credit goes to fightingforalostcause.net

/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD

Currency RegEx

Currency – U.S. Dollars and Cents with commas for multiple’s of 1000 and a period for the decimal:
$12,000.23

^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,} (\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$

Currency – British Pounds with commas for multiple’s of 1000 and a period for the decimal:
£12,000.23

^\u00A3?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,} (\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$

Currency – Euros with periods for multiple’s of 1000 and a comma for the decimal:
€12.000,23

^\u20AC?([1-9]{1}[0-9]{0,2}(\.[0-9]{3})*(\,[0-9]{0,2})?|[1-9]{1}[0-9]{0,} (\,[0-9]{0,2})?|0(\,[0-9]{0,2})?|(\,[0-9]{1,2})?)$

Currency – Euros, French style, with spaces for multiple’s of 1000 and a comma for the decimal:
€12 000,23

^\u20AC?([1-9]{1}[0-9]{0,2}(\s[0-9]{3})*(\,[0-9]{0,2})?|[1-9]{1}[0-9]{0,} (\,[0-9]{0,2})?|0(\,[0-9]{0,2})?|(\,[0-9]{1,2})?)$
]]>
https://phpreferencebook.com/tips/common-regular-expressions/feed/ 1
Testing Regular Expressions with Color Highlighting https://phpreferencebook.com/tips/regex-color-coding/ https://phpreferencebook.com/tips/regex-color-coding/#comments Thu, 16 Apr 2009 08:01:20 +0000 https://phpreferencebook.com/?p=236 Continue reading Testing Regular Expressions with Color Highlighting]]> Discovered a great website today while working on a complex Regular Expression: RegExPal.com. The site provides color code highlighting for RegEx syntax, including real-time evaluation of test data. If you, for instance, forget to include a closing or opening parenthesis for a group inside the regular expression, the orphaned parenthesis will be highlighted in red for easy identification of the error.

Here is a quick screenshot of some of the highlighting in action:
RegExPal Screenshot

Be advised that this is based on JavaScript regular expressions, which are comparable to the PERL compatible RegEx functions, such as preg_replace() and preg_match(). It’s a good idea to get familiar with this syntax, as ereg() and eregi() style functions will be removed from PHP6 when it is released, sometime in the future. Make sure to also checkout the Regular Expressions Cookbook contributed to by the author of RegExPal.com.

]]>
https://phpreferencebook.com/tips/regex-color-coding/feed/ 1
Use isset() Instead of strlen() https://phpreferencebook.com/tips/use-isset-instead-of-strlen/ Wed, 15 Apr 2009 04:35:04 +0000 https://phpreferencebook.com/?p=230 Continue reading Use isset() Instead of strlen()]]>

This tip is courtesy of a great article, 10 Advanced PHP Tips Revisited

When referencing an array’s value via a numeric key, you follow the variable name ($variable) with the numeric index, enclosed by square brackets [5]. e.g. $variable[5] = ‘value’
However, when $variable represents a string, using the same syntax will return a string with the character at the position specified by the numeric index (0 marks the first character in the $variable string). An example:

$string = 'abcdefg';
var_dump($string[2]);

Output: string(1) “c”

Where this comes into play is when using isset() rather than strlen(). Consider the following example:

$string = 'abcdefg';
if (isset($string[5])){
  echo $string[5].' found!';
}

Output: f found!

$string = 'abcdefg';
if (isset($string[7])){
     echo $string[7].' found!';
  }else{
     echo 'No character found at position 7!';
}

Output: No character found at position 7!

This is faster than using strlen() because, “… calling a function is more expensive than using a language construct.” It’s little tricks like this that will keep your code lean and efficient. Thanks to Chris Shiflett and Sean Coates for their contributions to the referenced article.

]]>
Display a Query String Value on a Web Page https://phpreferencebook.com/tips/display-query-string/ Tue, 13 Jan 2009 05:15:23 +0000 https://phpreferencebook.com/?p=57 Continue reading Display a Query String Value on a Web Page]]> It seems simple, almost basic, but many people want to display the contents of a query string on a page for the user or just for troubleshooting purposes. Everyone does it, everyone needs to do it, and there are a few different options I’m going to introduce below. First, our sample URL:

https://phpreferencebook.com/?variable=value&name=Mario%20Lurig&gender=male%21

or

https://phpreferencebook.com/?variable=value&name=Mario Lurig&gender=male!
  1. Display the whole string (everything after the question mark)
    • <?php echo $_SERVER['QUERY_STRING']; ?>
      • variable=value&name=Mario%20Lurig&gender=male
  2. Display the whole string decoded (convert %## to original characters)
    • <?php echo urldecode($_SERVER['QUERY_STRING']); ?>
      • variable=value&name=Mario Lurig&gender=male!
  3. Show each variable and value as an array (already decoded)
    • <?php print_r($_GET); ?>
      • Array ( [variable] => value [name] => Mario Lurig [gender] => male!
    • <?php echo '<pre>'; print_r($_GET); echo '< /pre>'; ?>
      • Array
        (
            [variable] => value
            [name] => Mario Lurig
            [gender] => male!
        )
        

There are lots of options from there, so don’t let this be the end of your exploration of how to display a query string value on a page. If you have any great tricks, feel free to share them in the comments below!

]]>