You are here: array_search troubles « PHP Programming Language « IT news, forums, messages
array_search troubles

Posted by JP on 01/08/08 21:05

Folks,

I'm having trouble interpreting the return value of the array_search
function. I'll give an example of my code and the output.

Basically, I'm trying to figure out how to check that no match was
found but no matter what I try checking on the return value, my code
keeps telling me that a match was found. I figured the array_search
is supposed to return the index key of the match so why can't I check
to see that the return value from array_search is >=0 and < the count
of the searched array? As you can see from this example, that does
not work? Any ideas of how to check the return value of
array_search()?


Here is the code:

<?php
$itemscols['COLUMN_NAME'][0] = 'CATNO';
$itemscols['COLUMN_NAME'][1] = 'FNAME';
$itemscols['COLUMN_NAME'][2] = 'MI';
$itemscols['COLUMN_NAME'][3] = 'LNAME';
$itemscols['COLUMN_NAME'][4] = 'PHONE';
$itemscols['COLUMN_NAME'][5] = 'EMAIL';
$itemscols['COLUMN_NAME'][6] = 'ADDR1';
$itemscols['COLUMN_NAME'][7] = 'ADDR2';
$itemscols['COLUMN_NAME'][8] = 'CITY';
$itemscols['COLUMN_NAME'][9] = 'STATE';
$itemscols['COLUMN_NAME'][10] = 'ZIP';
$itemscols['COLUMN_NAME'][11] = 'TITLE';
$itemscols['COLUMN_NAME'][12] = 'DESC';


$keys=array('CATNO','TITLE','LNAME');

var_dump($itemscols);
var_dump($keys);

foreach ($itemscols['COLUMN_NAME'] as $key)
{
$retval = array_search($key,$keys);
if ((int)$retval>=0) && (int)$retval<count($keys))
{
echo "Found key $key! \$retval=$retval\n";
}
else
{
echo "Did not find key $key! \$retval=$retval\n";
}
}
?>


The output from the above script is:
array(1) {
["COLUMN_NAME"]=>
array(13) {
[0]=>
string(5) "CATNO"
[1]=>
string(5) "FNAME"
[2]=>
string(2) "MI"
[3]=>
string(5) "LNAME"
[4]=>
string(5) "PHONE"
[5]=>
string(5) "EMAIL"
[6]=>
string(5) "ADDR1"
[7]=>
string(5) "ADDR2"
[8]=>
string(4) "CITY"
[9]=>
string(5) "STATE"
[10]=>
string(3) "ZIP"
[11]=>
string(5) "TITLE"
[12]=>
string(4) "DESC"
}
}
array(3) {
[0]=>
string(5) "CATNO"
[1]=>
string(5) "TITLE"
[2]=>
string(5) "LNAME"
}
Found key CATNO! $retval=0
Found key FNAME! $retval=
Found key MI! $retval=
Found key LNAME! $retval=2
Found key PHONE! $retval=
Found key EMAIL! $retval=
Found key ADDR1! $retval=
Found key ADDR2! $retval=
Found key CITY! $retval=
Found key STATE! $retval=
Found key ZIP! $retval=
Found key TITLE! $retval=1
Found key DESC! $retval=

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация