Skip to content

Some PHP functions to help your day

by Vinícius Krolow on agosto 16th, 2010

isset()

The function isset determine if a variable is set and is not NULL, okay that I guess evebody knows.

But the isset accept multiple parameters:

1
2
3
4
5
< ?php
	$var1 = 'test';
	var_dump(isset($var1, $var2, $var3));
	//it will show FALSE
?>
1
2
3
4
5
6
7
< ?php
	$var1 = 'test';
	$var2 = 1;
	$var3 = 'test3';
	var_dump(isset($var1, $var2, $var3));
	//it will show TRUE
?>

key(), prev(), current(), next()

Iterate one array is a thing very common in PHP, but normally I saw in the PHP code just two types of iterate the foreach (the most common) and the for using the loops, but we have also other ways one is using the functions that we have since php4.

1
2
3
4
5
6
7
8
< ?php
	$work = array('simple', 'hard', 'meddium', 'easy', 'fastly');
	var_dump(current($work)); //simple
	var_dump(next($work)); //hard
	var_dump(next($work)); //meddium
	var_dump(prev($work)); //hard
	var_dump(end($work)); //fastly
?>

For itearate for example:

1
2
3
4
5
6
7
< ?php 
	$brands = array('ford', 'nissan', 'toyota', 'kia');
	while (!is_null($key = key($brands))) {
		var_dump($key, current($brands));
		next($brands);
	}
?>

Or the reverse iterate:

1
2
3
4
5
6
7
8
< ?php 
	$brands = array('ford', 'nissan', 'toyota', 'kia');
	end($brands);
	while (!is_null($key = key($brands))) {
		var_dump($key, current($brands));
		prev($brands);
	}
?>

String functions that you must knows:

strcasecmp(), strncasecmp(), with these functions you can compare string, and the second you also set the number of characters to compare for example:

1
2
3
4
5
6
7
8
9
10
11
< ?php
	$string1 = '1111abcdefg';
	$string2 = '1111testando';
 
	// Compare the first four characters
	//Returns < 0 if string1 is less than string2; > 0 if string1 is greater than string2, and 0 if they are equal.
	//!0 == 1 (true)
	//!1 == 0 (false)
	//!-1 == 0 (false)
	echo !strncasecmp($string1, $string2, 3); 
?>

substr_compare(), compare using pieces of string, and determine the index and the number of characters:

1
2
3
< ?php 
	echo substr_compare("abcde", "bc", 1, 3); // 1
?>

The strpos is really common but one function that do a simmilar job and I didn’t see so much in the code is the strstr, that function searches the haystack for a needle. But the difference between strpos is that function return the portion of the haystack that starts with the needle instead of the latter’s position:

1
2
3
4
< ?php
	$string = "linkhere http://terra.com.br";
	echo strstr($string, 'http://');
?>

From → php

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS