how to Check values present in javascript array or not - php

here is my javascript array alert(Parameter); it alerts:
Eqt_Param0=4.00,Eqt_Param1=0,Eqt_Param2=0
Now what I am trying to do is if any of the array elements values are equal to '0` i need to alert 'array does not contain all values,', so how to check whether array is empty or not.

It looks like your array is a set of values of the form "key=number", and you want to know if any of the numbers are equal to zero.
The "proper" way to do it is:
var l = Parameter.length, i;
for( i=0; i<l; i++) {
if( Parameter[i].split("=")[0] == "0") {
alert("Array does not contain all values");
break;
}
}
But you could just hax it:
if( (Parameter.join(",")+",").indexOf("=0,") > -1) {
alert("Array does not contain all values");
}

Related

If any value of $_POST is empty

So I know how to error check an empty post value with an if empty combination, however how can this be done if the post data is an array and it needs to be applied to each value?
Example:
foreach (array($_POST['post_values']) as $test) {print_r($test); echo'<br />';};
where
<input name="post_values[value_1]">
<input name="post_values[value_2]"> etc.
I need to be able to say that if a value is not posted to any of the inputs, then that particular input = zero without applying a default value to the inputs themselves.
Therefore if value_1 = 5 and value_2 = blank, the array will show as 5 and 0.
Thanks in advance,
Dan
You can do something like this:
for ($i = 0; $i < count($_POST['post_values']); $i++){
if (empty($_POST['post_values'][$i])){
$_POST['post_values'][$i] = 0;
}
}
Would this work?
foreach ($_POST['post_values'] as $key=>$test) {
if($test==""){
$_POST["post_values"][$key]=0;
}
};
print_r($_POST['post_values']);
you can do the following. inside your look you can check for value
$value = (trim($test) != "" ? $test : 0);
echo $value; // if $test is blank then it would be 0 else would get value of $test.

Order Array by Relevant Search Results

I know that there has to be a library for this somewhere, but what I am trying to do is pass in an array of strings, and a search string and have it order the array by how relevant it is to the search string.
I have been having a hard time figuring out what to google to figure this out, anyone point me in the right direction?
preferably in php, or another server side language
I don't really know what you mean by 'revelant'..
But, if you want to find the best string based on a search string, you can use the Levenshtein algorithm. It calculate a "distance" between two strings.
More infos here : http://php.net/manual/fr/function.levenshtein.php
This is kinda tricky and I cannot really explain in English, so I'll just have to show you a working code. If you have an questions, you can ask.
<!DOCTYPE html>
<head>
<title>Search Array</title>
<script>
//so let's set an array of values we will be searching
function searchArray(dis) {
var bigContent = new Array('Jesus loves you','Angle','God in Heaven','Bala','Overcomer','Be born again','Adesuwa','Heaven is real','James','Apple','John the baptist');//this is the array that serves as your database
var searchi = dis.value, result = Array();
searchi = searchi.toLowerCase();
//order the array alphabetically
bigContent = bigContent.sort();
var content;
if(searchi !='') {
//Define the arrays for initial pre-storage
var keys = new Array(), contentArray = new Array();
//Loop through the content array to search for all occurence of string
for(var i=0;i<bigContent.length;i++) {
content = bigContent[i].toLowerCase();
if(content.indexOf(searchi) > -1) {//found the search in this value
//get the position of the search string in content
var pos = content.indexOf(searchi);
//make position the key for your content array
if(contentArray[pos]) {//check if this position has already been assigned to a content
//if yes, append this content.
contentArray[pos] += '[]'+bigContent[i];
} else {//else, set the content
contentArray[pos] = bigContent[i];
//only save the position the first time you find it, to avoid duplication
keys[keys.length] = pos;
}
}
}
//sort the key so it can order the values in ascending order(relevance)
keys = keys.sort();
//loop thru the key
for(var i=0;i<keys.length;i++) {
var key = keys[i];//remember the value of "var key" is the key for contentArray value
if(contentArray[key]) {//just to be sure it's ther
var thisContent = contentArray[key];
//check if the content has more than 1 value
if(thisContent.indexOf('[]') < 0) {//if it doesn't
result[result.length] = contentArray[key];
} else {//if it does
//convert content into array
var thisContentAr = thisContent.split('[]');
//Loop thru the array
for(var j=0;j<thisContentAr.length;j++) {
result[result.length] = thisContentAr[j];
}
}
}
}
}
document.getElementById('ov').innerHTML = '';
for(var i = 0; i<result.length;i++) {
document.getElementById('ov').innerHTML += '<div>'+result[i]+'</div>';
}
}
</script>
</head>
<body>
<div><input type="text" onkeyup="searchArray(this);" autofocus="autofocus" /></div>
<div id="ov"></div>
</body>
</html>

Passing by reference in AS3

How do I pass values by reference inside a for each construct in AS3? Basically, I want something equivalent to the following code in PHP:
foreach ($array as &$v) {
$v = $v + 1;
}
This would allow me to change all elements of the collection $array through a single loop.
Pointers don't exist in AS3 so you need to use Array.forEach method that executes a function on each item in the array:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html?filter_coldfusion=9&filter_flex=3&filter_flashplayer=10&filter_air=1.5#forEach%28%29
A bit off-topic but more info about values and references in AS3 (for functions)
In ActionScript 3.0, all arguments are passed by reference because all values are stored as objects. However, objects that belong to the primitive data types, which includes Boolean, Number, int, uint, and String, have special operators that make them behave as if they were passed by value.
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f56.html
You can not do this they way you do it in PHP. The for each loop will yield a reference variable v you can use to get the value, but setting v=v+1 would not change the original array, but erase the reference and set a new value only to v. But you can still modify all array values in one loop:
For a simple Array:
var array1 : Array = [ "one", "two", "three" ];
for (var i : int = 0; i < array1.length; i++)
{
array1[i] = "number " + array1[i];
}
For an associative array (it's actually an Object in Flash), use for...in:
var array2 : Object = { one:"one", two:"two", three:"three" };
for (var s:String in array2) // s is the string value of the array key
{
array2[s] = "number " + array2[s];
}
I think the second one is what you are looking for.
EDIT: weltraumpirat was correct. My original example wasn't modifying the contents of the original array which is probably what the original poster wanted. Here's some updated examples:
Updated example using for each:
for each (var s:String in arr)
{
arr[arr.indexOf(s)] = "<Your value here>";
}
Updated example using a standard for loop:
for (var counter:int = 0; counter < arr.length; counter++)
{
arr[counter] = "<your value here>";
}
Original example [Incorrect]:
for each (var s:String in array)
{
s = <your value here>;
}

matching array string values in nested for loop in PHP doesn't recognize condition

I am trying to strip out string values from array $error_message_key that match string values from array $err_strings. And then assign the strings that are left to $postback. The particular code that does the filtering in the function below is if($error_message_key[$e] != $err_strings[$g]) but it doesn't seem to work. I still get all the string values from array $error_message_key.
$err_strings = explode('+', $catch_value);
for($e = 0; $e < count($error_message_key); ++$e)
{
for($g = 0; $g < count($err_strings)-1; ++$g)
{
if($error_message_key[$e] != $err_strings[$g])
{
$postback .= '&'.$error_message_key[$e].'='.$_POST[$error_message_key[$e]];
}
}
}
UPDATE: Here are the arrays:
$error_message_key = array('email','firstName','lastName','pwd','username','phone','street','city', 'country', 'postal','province');
$err_strings = array('lastName','pwd','username');
Array $err_strings actually comes from explode'd string $catch_value which is in a form of "lastName+pwd+firstName+".
UPDATE:
The output should be in a form of:
$postback = 'lastName=value&firstName=value&phone=value&....'
UPDATE:
This is actually a script that responds if a user has wrong inputs in the form. The supposed to be stripped out string are names of the fields which would have the border color changed. The remaining string values are also names of the fields with correct inputs which would then be refilled with the same inputs... Please feel free to suggest another way of doing this if you think it's inappropriate...
Have you considered array_diff or array_intersect?
I was unable to determine if you want the strings the arrays have in common, or the ones they do not have in common, so use whichever one is appropriate.
(Disclaimer: untested code)
$entries = array_diff($error_message_key, $err_strings);
foreach($entries as $entry)
{
$postback .= '&' . $entry . '=' . $_POST[$entry];
}
You may want to wrap the values with urlencode if you are using this as a url.
Of course you get all of the strings. Indeed, don't you find that you get a ridiculous number of them in your output string, with many of them doubled/tripled/etc?
For each value in $error_message_key, you check every value of $err_strings for being not equal to the current value. That means that for (from the start) 'email', your code goes: "checking email against lastName... they're not equal, so add it. Now checking email against pwd... they're not equal, so add it. Now..." etc.
For an example, try running this slight alteration of your given code, which just adds echo to it:
<?php
$postback = "";
$error_message_key = array('email','firstName','lastName','pwd','username','phone','street','city', 'country', 'postal','province');
$err_strings = array('lastName','pwd','username');
for($e = 0; $e < count($error_message_key); ++$e)
{
for($g = 0; $g < count($err_strings); ++$g)
{
echo "Comparing ".$error_message_key[$e]." against ".$err_strings[$g]."<br />";
if($error_message_key[$e] != $err_strings[$g])
{
$postback .= '&'.$error_message_key[$e];// Scrapped because no $_POST. .'='.$_POST[$error_message_key[$e]];
}
}
}
?>
I think you'll find the output informative as to your problem.

assigning value to array in javascript

in php you could do like this:
$key1 = 1;
$key2 = 1;
$array[$key1][$key2] = 'hi';
in javascript i tried with this:
key1 = 1;
key2 = 1;
var array = new Array();
array[key1][key2] = 'hi';
but it didnt work. how can i do the same thing in javascript?
Your problem is that you need to instantiate the inner array before assigning values in it
var key1 = 1;
var key2 = 1;
var array = [];
array[key1]=[];
array[key1][key2] = 'hi';
Or you could do it all in one:
var array=[['hi']]
Also, you should avoid assigning to specific indexes unless you're updating an existing element. The first example above will automaticly add an element
array[0]=undefined;
If you want to use specific keys, and not just indexes, you should use dictionaries or objects (dictionaries and objects are the same thing i javascript)
The key1 property of array is undefined at the time you are trying assign the property key2 to it. You need to actually indicate that array[key1] is an array before you start assigning values to it.
For example:
array[key1] = [];
array[key1][key2] = 'hi';
JavaScript is having a problem with the key1 and key2 dimensions of your array being undefined. To correct this problem, these are changes you could make:
var key1 = 1;
var key2 = 1;
// define "array" as an empty array:
var array = [];
// define "array[key1] as an empty array inside that array
// (your second dimension):
array[key1] = [];
array[key1][key2] = 'hi';
PHP does some magic -- you can simply supply 2 keys and PHP "knows what you mean" and will define the $key1 and $key2 dimensions without thinking about it. See: PHP: arrays: If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key.
JavaScript requires you to be more explicit about array creation.
You can find neat implementations. For example, here is a way, which is a function creating an array for the rows and then, creating an array for each column (could be anidated in the other way, but...)
var sDataArray=MultiDimensionalArray(7,2);
//alert(sDataArray[0][0]);
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
var a = new Array(iRows);
for (i=0; i < iRows; i++)
{
a[i] = new Array(iCols);
for (j=0; j < iCols; j++)
{
a[i][j] = "";
}
}
return(a);
}
The thing is, you just can't work the arrays just like PHP ones. Must treat them the way they really are: an array of arrays (of arrays (of arrays (of arrays)...)).
Good luck.

Categories