array_count_values for float values 1

Posted by Lloyd on December 11, 2010 at 2:04 pm

Nerd Talk

array_count_values function in PHP can only count integer and string values. At some point you may need to count occurrences of float values in an array but you can’t because array_count_values won’t let you. If you have an array like:

$digits = array(14.5, 5.42, 1.5, 8, 14.5);
$digits = array_count_values($digits);

This will give you a warning that says, Warning: array_count_values() [function.array-count-values]: Can only count STRING and INTEGER values!

There’s actually a hack to get around this and achieve counting occurrences of float values. All you need to do is cast all float values in the array as string. array_count_values can also count integers so why not just cast the values as int? You don’t want to do that because casting the float values as int will change the data type to int but also remove the decimal points in your values and make it a whole number. Take this as an example:

$float = 12.8;
var_dump($float);         // float(12.8) - original float value
var_dump((int)$float);    // int(12) - becomes whole number
var_dump(intval($float)); // int(12) - becomes whole number
var_dump((string)$float); // string(4) "12.8" - string type

Based on the example above we need to cast the float values as string. So in the case of the array that we want to count the values, we need to do something like:

$digits = array(14.5, 5.42, 1.5, 8, 14.5);
$newDigits = array();
foreach($digits as $key => $value)
	// cast float as string
	if(is_float($value))
		$newDigits[$key] = (string)$value;
	// for actual int and string values
	else
		$newDigits[$key] = $value;
 
$countValues = array_count_values($newDigits);
print_r($countValues);

The above code will cast all float values in the array as string and array_count_values will work as expected. The output will be:

Array
(
    [14.5] => 2
    [5.42] => 1
    [1.5] => 1
    [8] => 1
)

Hope that helps!

Weekend Hibernation 2

Posted by Lloyd on September 04, 2010 at 12:11 pm

Finally I can sleep more and will sleep more! Last week we had a crazy schedule and been busier than ever. No time to visit social networks and no time to blog. No time to watch TV and no time to text people, even just to say Hi. Daily routine is to take a nap, eat (snacks), take a bath, and then go back to work. I remember only eating once a day because I’m so sleepy that when I got home all I want is sleep. Really some ass-busting week for us. It was good, we get to finish what we need but it’s just a start. More work coming up! Ok, I have to sleep.

Ajax search execution interval 2

Posted by Lloyd on July 11, 2010 at 9:28 pm

Nerd Talk

Search functionality can be done in two ways, (1) the usual form submit that reloads the page to submit the query and (2) through Ajax, doesn’t require a page reload because it sends the query in the background which is cool. If you’re working on a search functionality it is best to always optimize the process because every time the user hits the submit button your server gets hit in the head to perform the request. As we know, searching requires database query and we don’t want to request from the database that often because it’ll bite you in the ass when there’s a lot of searches going on. In this post I won’t be providing tips on how to optimize search queries or any caching methods but this is a start for an optimized search functionality. This is to help you save server requests if you’re working on a similar search functionality.

If you’re working on a search functionality that triggers onkeyup:

<input onkeyup="Search(this)" name="search" />

You know, the kind of search functionality where you submit the request to the server when the user stops typing the keyword to save them time clicking the submit button or if you don’t have a submit button at all. When doing this we must make sure that we only submit or send the request to the server once the user had stopped typing. So if the user wanted to search for ‘krispy kreme’, take note if you’re using onkeyup event, your Search() function will get triggered every time your user lifts his finger off the keyboard key. Imagine the amount of request you’re sending to the server when searching for ‘krispy kreme’, that’s 12 characters, 12 Ajax requests. Code below will help to only send a request to the server when the user had stopped typing, we assume that the user already finished typing the search keyword.

// initial interval value
var SearchTimeOut = 0;
// how long before the execution starts; in milliseconds (1000 = 1 second)
// just the value i'm happy with, not too fast or slow
// increase value if you think users type 1 ltr (letter per second) &gt;:)
var Interval = 333;
 
// stores the search keyword
var CurrentSearchKey = '';
var Search = function(obj) {
	// get the keyword from the field
	var keyword = obj.value;
 
	// cancel the previous search
	// SearchTimeOut contains a value more than zero when assigned with
	// a setTimeout()
	if(SearchTimeOut > 0)
		ResetSearch();
 
	// we only start a request when the search keyword is different from
	// the current keyword
	if(CurrentSearchKey == keyword)
		return;
 
	// the magic, we attach the search process to setTimeout to put in an
	// interval every time the Search() is executed
	// setTimeout() returns a value assigned to SearchTimeOut everytime
	// it's called since SearchTimeOut now holds whatever StartSearch()
	// is doing when we do a keyup event, everytime we execute Search()
	// we will cancel SearchTimeOut and start a new one, that's what makes
	// sending a request to the server lesser because we only do a request
	// to the server when we stop typing a keyword
	SearchTimeOut = setTimeout("StartSearch('"+keyword+"')", Interval);
}
 
// the actual search function
var StartSearch = function(keyword) {
	CurrentSearchKey = keyword;
	// here is where you put your Ajax request code, regardless if you're
	// using jQuery, Prototype JS, or the conventional way of doing Ajax
}
 
// cancels the previous search interval
var	ResetSearch = function() {
	// this is what cancels the setTimeout interval assigned
	// to SearchTimeOut
	clearTimeout(SearchTimeOut);
	SearchTimeOut = 0;
}

There you have it, hope that helps! :)

JavaScript prototype object not working 3

Posted by Lloyd on May 15, 2010 at 2:46 pm

If you happen to be working on a custom object and using the prototype property of JavaScript to add custom methods but it doesn’t seem to work, the solution is simple, you just need to instantiate your custom object by using the new keyword so all the custom methods through the prototype object are added.

// Sample custom object
var CustomObject = function() {
	this.props = {
			property: 'value'
		}
}
 
CustomObject.prototype = {
	CustomMethod: function() {
		alert(this.props.property);
	}
}
// Instantiate the custom object
var foo = new CustomObject;
// Doing that enables you to do this
foo.CustomMethod(); // alerts 'value'
 
// will not work because the object is not created as a new instance
// prototype methods not yet added to CustomObject
CustomObject.CustomMethod();

HTH :)

just a rant

Posted by Lloyd on August 22, 2009 at 9:53 pm

Instructors/teachers/whatever you call them, I have no idea and sometimes it makes me think why they’re twisted as hell – or maybe just some of them. I just want to rant because a friend of mine worked hard with her programming assignment and as a programmer myself I think that she did a good job after seeing some of her codes (just a sneak). She told me that she got a low score for her work because she used advanced coding style. I dunno but her teacher should be happy about it but gave her a low score because he told her that the way she wrote her code was advanced and not yet discussed in the class. That’s just insane. They ask you to research and do something and when you do it more than what they expect, they would say, “this is not yet discussed, out of the scope of our lesson”. And then at some point they will ask you do a project and they expect you to do something beyond imaginable and you can’t do it because they didn’t discuss it in class, they would say “you have to research”. I hope you get the idea. And while I’m in the topic, this is one reason why I hate going back to school, I hate going all the trouble of finishing something and in the end it seems your work just didn’t pay off. Just sucks.

Programming

Posted by Lloyd on July 09, 2009 at 12:57 pm

Programming can be the most stressful, hairpulling experience, when you find the solution, the most glorious.

- @rogieking

Code Quality

Posted by Lloyd on June 03, 2009 at 8:39 am

‘Back to top’ link using jQuery 40

Posted by Lloyd on May 19, 2009 at 3:56 pm

If you noticed I have a ‘Back to top’ link appearing at the bottom right everytime you scroll down the page. Wonder how it was made? I’ll tell you. It’s quite simple. What you need is a div containing the text, apply some css and add an event using jQuery.

First, create the div:

<div id="toTop">^ Back to Top</div>

Then add style to it, add this in your css file or inside <style> tag:

#toTop {
	width:100px;
        border:1px solid #ccc;
        background:#f7f7f7;
        text-align:center;
        padding:5px;
        position:fixed; /* this is the magic */
        bottom:10px; /* together with this to put the div at the bottom*/
        right:10px;
        cursor:pointer;
        display:none;
        color:#333;
        font-family:verdana;
        font-size:11px;
}

And last, the jQuery code:

<script src="path/to/js/jquery.js"></script>
<script type="text/javascript">
$(function() {
	$(window).scroll(function() {
		if($(this).scrollTop() != 0) {
			$('#toTop').fadeIn();	
		} else {
			$('#toTop').fadeOut();
		}
	});
 
	$('#toTop').click(function() {
		$('body,html').animate({scrollTop:0},800);
	});	
});
</script>

There you have it! Simple isn’t it? :)
This works in Firefox 3.0.10 – 3.6.13, Internet Explorer 7 (Strict Mode) and 8, Google Chrome, jQuery 1.4.3.

Remember: On IE 7, your page needs to be at strict mode, just add a doctype at the top of your page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Hope that helps :)

Sorry no IE 6 support and also I think it doesn’t work in Quirks Mode (will see if it’s possible) :(

Let me know if something is missing in the code sample, for some reason it always gets deleted every time I update the post in the visual editor.

Check a working sample here.

Comments closed due to spamming. If you have questions, please send me an email which can be found here.


^ Back to Top