...

View Full Version : Check if array contains variable



supersav144
12-15-2010, 03:28 PM
I am currently trying to check using javascript whether a php array contains a variable, and if it does then display a message.

Any help would be much appreciated.

I have written the following code...




<?php
//php which sets users array to the results of the sql
$selectquery = "SELECT Username FROM User";
$selectresult = mysql_query($selectquery);
while ($row = mysql_fetch_array($selectresult)){
$users[] = $row['Username'];

}
?>



<script language="javascript" type="text/javascript">
function verifyUsername(array_var){

var user = document.getElementById("username").value;

for(var i=0; i<array_var.length; i++){
if(array_var[i] == user){
document.getElementById("usernameerror").textContent = "already in array";
}
}
}
</script>



//html code for the form
Username: <input type="text" name="username" id="username" onblur="return verifyUsername(<?php $users?>)"/>

<span id="usernameerror" class="red"></span>

Rowsdower!
12-15-2010, 03:55 PM
In order for javascript to check your array from the PHP code you would have to write that array to the page (as javascript).

It would look something like this (I haven't tested this so you may need to clean up a bit):

<?php
//php which sets users array to the results of the sql
$selectquery = "SELECT Username FROM User";
$selectresult = mysql_query($selectquery);
while ($row = mysql_fetch_array($selectresult)){
$users[] = $row['Username'];

}
?>
<script type="text/javascript">
var the_list_from_php=new Array();
<?php
for($i=0;$i<count($users);$i++){
//print out variable data to create the items in the javascript array...
print "the_list_from_php[".$i."]='".$users[$i]."';\n";
}
?>
</script>

Then you just need to check the array named "the_list_from_php" to see if the value you are testing for exists in the array.

Let me know if you have questions.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum