473,804 Members | 2,249 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

array_search() not working correctly?

Daz
Hi everyone. I am having a problem with array_search(). My php script
gets a list of books from the database, and then compares them with a
list of books which have been obtained from a textarea in a form, and
formatted into single books, each one stored in a non-associative
array.

I have a function that compares the books in the $user_books array, to
those in the array derived from the books that are in the database.

If a book exists in the database, then it needs to be added to the user
table, for this I need the book id. If it doesn't the user will be
given a list of such books, displaying the names of the books that
aren't in the database.

If I created the list my making an array manually of both user books,
and books that are in the database, everything works fine, however, as
things are, array_search() won't return the key, if the book title has
a number in it.

I have posted my script below. I know it looks big and messy, but I
just wanted to know if anyone could spot any errors that may be leading
to the problem I am experiencing. I generally try to keep the script
simple, and then once it's doing what I want, I then work on optimizing
it.

<?php
$input = (isset($_POST['input'])) ? $_POST['input'] : '';

function validateBooks(& $booklist) {
global $db;
if ($booklist) {
$query =
"SELECT `book_name` AS name, `book_id` AS bid FROM
`pp_books`;";
$dbbooks_res = $db->sql_query($que ry);
$newbooklist = array();
$dbbooks = array();
while ($book = $db->sql_fetchrow($ dbbooks_res)) {
$book_name = $book['name'];
$dbbooks[$book['bid']] = $book_name;
}
foreach ($booklist as $book_name) {
$book_name;
$key = array_search("$ book_name", $dbbooks);
echo "key:$key<b r />";
if ($key) {
$newbooklist['valid'][] = $key;
}
else {
$newbooklist['invalid'][] = $book_name;
}
}
echo "Add<br />";
echo "<pre>",print_r ($newbooklist['valid']),"</pre>";
echo "Don't add<br />";
echo "<pre>",print_r ($newbooklist['invalid']),"</pre>";
}
}

function process($input= '') {
if ($input) {
$input = preg_replace("/([\n\r]|.+) Special Books \][\n\r]/s",
"", $input);
$input = preg_replace("/\[ .+/s", "", $input);
$input = preg_replace("/[\r\n]+/", "\n", $input);
$input_lines=pr eg_split("/\n/", $input);
$sizeof_input_l ines = sizeof($input_l ines);
$book_list = array();
for ($i=0; $i<$sizeof_inpu t_lines; $i++) {
if (strlen($input_ lines[$i])>1) {
$book_list[] = $input_lines[$i];
}
}
$books = sizeof($book_li st);
$not_added = validateBooks($ book_list);
}
}

echo "<center><subti tle>Import Books</subtitle></center><p>&nbsp ;</p>";
echo "<table>";
if ($input) {
process($input) ;
}

echo "<tr><td>".show ImportBox()."</td></tr>";
echo "</table>";

function showImportBox() {
global $module_name;
echo <<<EOT
<form method="post" action="index.p hp?name=$module _name">
<center><textar ea name="input" cols="80"
rows="30"></textarea></center><br />
<center><inpu t type="submit" name="submit_im port" value="Import
Books"></center>
<input type="hidden" name="do" value="Import My Books">
<input type="hidden" name="Import My Books" value="1">
</form>
EOT;
}

?>

Oct 17 '06 #1
2 3418
Can you give us examples as to what titles work and what titles don't?
It only doesn't work when there's a number in the book title? What does
array_search return?

a good debug idea would be to print the value of $book_name each time
you are about to run an array_search().
Daz wrote:
Hi everyone. I am having a problem with array_search(). My php script
gets a list of books from the database, and then compares them with a
list of books which have been obtained from a textarea in a form, and
formatted into single books, each one stored in a non-associative
array.

I have a function that compares the books in the $user_books array, to
those in the array derived from the books that are in the database.

If a book exists in the database, then it needs to be added to the user
table, for this I need the book id. If it doesn't the user will be
given a list of such books, displaying the names of the books that
aren't in the database.

If I created the list my making an array manually of both user books,
and books that are in the database, everything works fine, however, as
things are, array_search() won't return the key, if the book title has
a number in it.

I have posted my script below. I know it looks big and messy, but I
just wanted to know if anyone could spot any errors that may be leading
to the problem I am experiencing. I generally try to keep the script
simple, and then once it's doing what I want, I then work on optimizing
it.

<?php
$input = (isset($_POST['input'])) ? $_POST['input'] : '';

function validateBooks(& $booklist) {
global $db;
if ($booklist) {
$query =
"SELECT `book_name` AS name, `book_id` AS bid FROM
`pp_books`;";
$dbbooks_res = $db->sql_query($que ry);
$newbooklist = array();
$dbbooks = array();
while ($book = $db->sql_fetchrow($ dbbooks_res)) {
$book_name = $book['name'];
$dbbooks[$book['bid']] = $book_name;
}
foreach ($booklist as $book_name) {
$book_name;
$key = array_search("$ book_name", $dbbooks);
echo "key:$key<b r />";
if ($key) {
$newbooklist['valid'][] = $key;
}
else {
$newbooklist['invalid'][] = $book_name;
}
}
echo "Add<br />";
echo "<pre>",print_r ($newbooklist['valid']),"</pre>";
echo "Don't add<br />";
echo "<pre>",print_r ($newbooklist['invalid']),"</pre>";
}
}

function process($input= '') {
if ($input) {
$input = preg_replace("/([\n\r]|.+) Special Books \][\n\r]/s",
"", $input);
$input = preg_replace("/\[ .+/s", "", $input);
$input = preg_replace("/[\r\n]+/", "\n", $input);
$input_lines=pr eg_split("/\n/", $input);
$sizeof_input_l ines = sizeof($input_l ines);
$book_list = array();
for ($i=0; $i<$sizeof_inpu t_lines; $i++) {
if (strlen($input_ lines[$i])>1) {
$book_list[] = $input_lines[$i];
}
}
$books = sizeof($book_li st);
$not_added = validateBooks($ book_list);
}
}

echo "<center><subti tle>Import Books</subtitle></center><p>&nbsp ;</p>";
echo "<table>";
if ($input) {
process($input) ;
}

echo "<tr><td>".show ImportBox()."</td></tr>";
echo "</table>";

function showImportBox() {
global $module_name;
echo <<<EOT
<form method="post" action="index.p hp?name=$module _name">
<center><textar ea name="input" cols="80"
rows="30"></textarea></center><br />
<center><inpu t type="submit" name="submit_im port" value="Import
Books"></center>
<input type="hidden" name="do" value="Import My Books">
<input type="hidden" name="Import My Books" value="1">
</form>
EOT;
}

?>
Oct 17 '06 #2
Daz

maven22 wrote:
Can you give us examples as to what titles work and what titles don't?
It only doesn't work when there's a number in the book title? What does
array_search return?

a good debug idea would be to print the value of $book_name each time
you are about to run an array_search().
Daz wrote:
Hi everyone. I am having a problem with array_search(). My php script
gets a list of books from the database, and then compares them with a
list of books which have been obtained from a textarea in a form, and
formatted into single books, each one stored in a non-associative
array.

I have a function that compares the books in the $user_books array, to
those in the array derived from the books that are in the database.

If a book exists in the database, then it needs to be added to the user
table, for this I need the book id. If it doesn't the user will be
given a list of such books, displaying the names of the books that
aren't in the database.

If I created the list my making an array manually of both user books,
and books that are in the database, everything works fine, however, as
things are, array_search() won't return the key, if the book title has
a number in it.

I have posted my script below. I know it looks big and messy, but I
just wanted to know if anyone could spot any errors that may be leading
to the problem I am experiencing. I generally try to keep the script
simple, and then once it's doing what I want, I then work on optimizing
it.

<?php
$input = (isset($_POST['input'])) ? $_POST['input'] : '';

function validateBooks(& $booklist) {
global $db;
if ($booklist) {
$query =
"SELECT `book_name` AS name, `book_id` AS bid FROM
`pp_books`;";
$dbbooks_res = $db->sql_query($que ry);
$newbooklist = array();
$dbbooks = array();
while ($book = $db->sql_fetchrow($ dbbooks_res)) {
$book_name = $book['name'];
$dbbooks[$book['bid']] = $book_name;
}
foreach ($booklist as $book_name) {
$book_name;
$key = array_search("$ book_name", $dbbooks);
echo "key:$key<b r />";
if ($key) {
$newbooklist['valid'][] = $key;
}
else {
$newbooklist['invalid'][] = $book_name;
}
}
echo "Add<br />";
echo "<pre>",print_r ($newbooklist['valid']),"</pre>";
echo "Don't add<br />";
echo "<pre>",print_r ($newbooklist['invalid']),"</pre>";
}
}

function process($input= '') {
if ($input) {
$input = preg_replace("/([\n\r]|.+) Special Books \][\n\r]/s",
"", $input);
$input = preg_replace("/\[ .+/s", "", $input);
$input = preg_replace("/[\r\n]+/", "\n", $input);
$input_lines=pr eg_split("/\n/", $input);
$sizeof_input_l ines = sizeof($input_l ines);
$book_list = array();
for ($i=0; $i<$sizeof_inpu t_lines; $i++) {
if (strlen($input_ lines[$i])>1) {
$book_list[] = $input_lines[$i];
}
}
$books = sizeof($book_li st);
$not_added = validateBooks($ book_list);
}
}

echo "<center><subti tle>Import Books</subtitle></center><p>&nbsp ;</p>";
echo "<table>";
if ($input) {
process($input) ;
}

echo "<tr><td>".show ImportBox()."</td></tr>";
echo "</table>";

function showImportBox() {
global $module_name;
echo <<<EOT
<form method="post" action="index.p hp?name=$module _name">
<center><textar ea name="input" cols="80"
rows="30"></textarea></center><br />
<center><inpu t type="submit" name="submit_im port" value="Import
Books"></center>
<input type="hidden" name="do" value="Import My Books">
<input type="hidden" name="Import My Books" value="1">
</form>
EOT;
}

?>
I don't believe it! I have figured out why it's not working, and man,
do I feel silly?

The books aren't in the database. It just happened to be that not a
single one of these 6 books were in there and they happened to be the
only 6 in my query containing numbers...

Thanks for your input, and sorry for wasting any of your time.

Sincerest regards.

Daz.

Oct 17 '06 #3

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

Similar topics

4
3350
by: Phil Powell | last post by:
Hi, I am basing this upon my study of the array_search and array_keys functions in www.php.net and www.zend.com and www.nyphp.org. I have this array, $this->propertyArray, which I have passed into a class as a mocked-up version of the same formatting as _GET and _POST arrays inasmuch as the keys are variable names and vals are the variable values. Here is the print_r printout of $this->propertyArray for example: Array (
0
1901
by: Don Leckie | last post by:
Hi, I'm upgrading our software from JDK 1.3.1_03 to JDK 1.4.2_07 and I'm having trouble with ComponentOrientation.RIGHT_TO_LEFT working correctly in a JScrollPane. One of my windows has a JSplitPane. There is a JScrollPane in each side. There's a JTable in each scroll pane. The left scroll pane has the vertical JScrollBar on the left side. The right scroll pane has the veritcal JScrollBar on the right side (default).
2
6721
by: Kamyk | last post by:
Hello all! Could you tell me where is the error on the below code, because the script is sometimes working correctly and sometimes is not working correctly. I want my new window with picture to be fitted/enlarged to original size. The page on the below address: http://www.kapy.bydg.pl/~marcinz/stolarnia/. I have Windows XP and IE 6.0. and everything works correctly. If I run the page on Win 2000, IE 5.0.
10
1872
by: Scott Richards | last post by:
Hi I am getting a exception while using a datareader here is the code Me.SqlConnection1.Open() Me.SqlReservationCheck.Parameters("@Ref").Value = Ref Dim Reader As SqlClient.SqlDataReader = _ Me.SqlReservationCheck.ExecuteReader() Dim I As Integer() Dim Index As Integer = 0 If Reader.HasRows Then While Reader.Read()
8
2539
by: jojobar | last post by:
Okay, I am trying to do is to test the webresource in 2.0 1. I created a new project with assembly name (and default assembly name) "Office". 2. I added the following to the AssemblyInfo.cs file (present under the Properties folder of the project) 3. Now I created a file called test.js on the root folder of the project,
9
3222
by: MSDNAndi | last post by:
Hi, I have a set of simple webservices calls that worked fine using .NET Framework 1.0. I am calling a Java/Apache based webservices, the calling side is not able to supply a proper WSDL. What it does is to call a webservice with two parameters, one being a integer, the other one being a "String" which contains XML (not the best practice, however that is the target interface and we cannot change that).
1
1731
by: Johnnyboy01 | last post by:
Hi all... I am having problems with the array_search function. No matter what I do, I can't get it to find a value that I specify. Here is the code I am using to call it: $value = 'month'; $key= array_search($value, $array); Yet, it won't work, I have done it using the value itself, itstead of a variable, and I have searched for several different things that I know are in the array. I also have a question aboud the array_search...
2
10334
hsriat
by: hsriat | last post by:
Is there any function in JS similar to array_search() of PHP which returns the key that contains the particular value, passed as argument. Or I need to make it myself?
1
2060
by: Mark B | last post by:
This is my first try at using AJAX. I want the calendars to be enabled if the user checks CheckBox1. It works OK for a normal all page refresh but once I introduced the AJAX code it stopped working. Any ideas? <%@ Page Language="VB" AutoEventWireup="false" CodeFile="default-ajax.aspx.vb" Inherits="pages_verify_groups_Default" Debug="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10090
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...
1
7635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5531
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
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
2
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.