473,606 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to avoid in_array() function.

Hi,
i've been always used the in_array() function to check availabylity of a
value in array. Until today. Simple code: (do not run it tho :) )

<?
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime ());
return ((float)$usec + (float)$sec);
}

$time_start = getmicrotime();

$first=range("a ","z");
$second=range(" a","z");
$third=range("a ","z");
$all_arr=array( );

foreach ($first as $f){
foreach ($second as $s){
foreach ($third as $t){

$ind=$f.$s.$t;
if (!in_array($ind ,$all_arr)) $all_arr[]=$ind;
}
}
}
$time_end = getmicrotime();
$time = $time_end - $time_start;
echo $time;
?>

It prints the time script worked. Guess the number?
250(!!!!) seconds!!!
Is there any alternative in PHP to check array?


--
Exact Meta Search | Major Search Engine http://exactsearcher.com
Web Design Essex | Multimedia | Printing http://nextwave.co.uk
Dec 4 '05 #1
6 3278
Berimor wrote:
It prints the time script worked. Guess the number?
250(!!!!) seconds!!!
Is there any alternative in PHP to check array?


There is array_search, but I didn't benchmark it.

HTH.
Peter.

--
http://www.phpforums.nl
Dec 4 '05 #2
On Sun, 04 Dec 2005 16:36:43 +0100, Peter van Schie
<va************ @gmail.com> wrote:
Berimor wrote:
It prints the time script worked. Guess the number?
250(!!!!) seconds!!!
Is there any alternative in PHP to check array?
There is array_search, but I didn't benchmark it.


i did - the same.
HTH.
Peter.


--
Exact Meta Search | Major Search Engine http://exactsearcher.com
Web Design Essex | Multimedia | Printing http://nextwave.co.uk
Dec 4 '05 #3
The hash table was invented precisely to solve this sort of problem.

Example:

$first=range("a ","z");
$second=range(" a","z");
$third=range("a ","z");
$all_hash=array ();

foreach ($first as $f){
foreach ($second as $s){
foreach ($third as $t){
$all_hash[$f.$s.$t] = true;
}
}
}
$all_arr = array_keys($all _hash);

Dec 4 '05 #4
On 04/12/2005 15:34, Berimor wrote:

[snip]
$first=range("a ","z");
$second=range(" a","z");
$third=range("a ","z");
$all_arr=array( );

foreach ($first as $f){
foreach ($second as $s){
foreach ($third as $t){
$ind=$f.$s.$t;
if (!in_array($ind ,$all_arr)) $all_arr[]=$ind;
}
}
}
[snip]
It prints the time script worked. Guess the number?
250(!!!!) seconds!!!
I'm not that surprised, though it took just less than a minute here. Do
you understand how much work you're expecting PHP to do?

In each iteration of the innermost loop, 'ind' will be assigned a unique
value. The in_array function must then search 'all_arr' and attempt to
find it. As it will never exist, the function will perform an exhaustive
search, eventually returning false.

In the first iteration, 'all_arr' will be empty. In the second, it will
have one element. By the final iteration, 'all_arr' will contain 17,575
elements (the final one yet to be added). To reach, and finally execute,
the final assignment, the in_array function will have performed
154,449,100 string comparisons (the sum of the number of elements on
each iteration) without a single match. The rest of the code will have
its own overheads, too.
Is there any alternative in PHP to check array?


It would seem that a better algorithm is what you really need. On this
machine, removing the if statement reduced the execution time to about
60ms: approximately 93 times faster.

Why do you think you need to keep checking the values in the array? If
you explain what you're doing, someone may be able to show you an
alternative approach.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Dec 4 '05 #5
Berimor wrote:
Is there any alternative in PHP to check array?


foreach ($first as $f){
foreach ($second as $s){
foreach ($third as $t){
$all_arr[] = $f.$s.$t;
}
}
}
$all_arr = array_unique($a ll_arr);
JW
Dec 4 '05 #6
Berimor wrote:
Hi,
i've been always used the in_array() function to check availabylity of a
value in array. Until today. Simple code: (do not run it tho :) ) <snip> It prints the time script worked. Guess the number?
250(!!!!) seconds!!!
Is there any alternative in PHP to check array?


IIRC, Ilia Alshanetsky, one of the PHP core developer and maintainer
blogged on this some time ago. According to him, isset() will be the
fastest; but for isset(), you need key.

FWIW, it's nice to see many people have now become optimization
advocates recently in c.l.php--a very rarest gesture some years ago:)

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/

Dec 5 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
6000
by: AJ Z | last post by:
I am using in_array() to search for a value ("other"), in order to validate a form. If I pass $_POST as the array to search PHP says that it is an invalid datatype. It is an array and if I copy it to another variable (i.e. $list = $_POST;) it works fine. The same is also true of implode(). Do you believe this is intended or is it a bug? --
2
1984
by: Mountain Man | last post by:
Hi, The in_array function sometimes malfunctions on my computer yielding the error message shown below. The code shown below usually works, but sometimes doesn't. This even happens with the same instance of code. Different results on different times I load the same page. Can anyone explain what's going on here? Best wishes,
3
10685
by: Phil Powell | last post by:
if (is_array($_POST)) { foreach ($this->getAssocSectionsObjArray($key, $dbAP) as $obj) { print_r($obj); print_r(" in array? "); print_r(in_array($obj, $result)); print_r("<P>"); if (!in_array($obj, $result)) array_push($result, $obj); } }
6
4041
by: Craig Keightley | last post by:
I am trying to compare values of a string entered into an array but having no results, is this possible to achieve: <?php $ids = $row_rsProduct; // A comma separated list of values (1,2,3,4,5,6,7,8) $list = array($ids); if (in_array(1, $list)) { echo "In List";
3
2265
by: Tom Barnes | last post by:
Check out this code: // Start Code ------------- function test_in_array($val) { $a = array('key' => $val); printf("in_array: %d, value:%s<BR>", in_array('key', $a), $a); } test_in_array(0); test_in_array(1);
3
1787
by: rich | last post by:
I keep getting the error: Warning: in_array(): Wrong datatype for second argument on line 679 here is the code. I declare and fill the array $specprimA = array(); $specprimA= getspecprim($dresstypeid); $primsecA=getprimsec(); Then I do a compare using in Array. I even put in the extra step of making sure I have something in the array with the is sizeof statement.
3
1884
by: Sonnich | last post by:
The following code is an exact copy of my current code. The idea is to check 2 parts (of string arrays), and add those only once to a common array. I check for existance of an array in a string, as the string contain more data that just .... well, the part from the options array is there, then it is added to the folders array. The problem is the line: if(!in_array($folders, $options1)) which works in the first case, but not...
9
6117
by: Dhiru1009 | last post by:
Hi guys, I am trying to build a user registration form using PHP and MYSQL but encountring a problem. When I click on submit with empty fields it adds records to database also it doesn't matter what information I put it always add records to database when I click on submit. What can I do to make sure user will not be able to add records to database until he enters the right information? I am posting my code for you guys to have a look...
0
1402
by: samz | last post by:
Hello, Here is a simple PHP recursive file list (with interactive and visual FX) Sam's Files http://acc.jexiste.ch/JPN/RecurciveDIR12.RAR 1. How to ignore/avoid empty folders in this PHP script ? 2. How to sort files by filename (and, if possible, folders on top) ? 3. Is this MAILTO hidden tool still useful against the current Spam robots ? Mysterious Ways - Hide Email Addresses from Spam Harvesters 4. Is my SpamPoison tag useful if I...
0
8009
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8428
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8078
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8299
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6753
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3919
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3964
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2442
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1548
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.