I have an array
$results = array(101, 102, 103, 104, 105)
I also have a input field where the user enters a number
<input type ="text" name="invoice" />
I put what the number that user enters in, into a variable
$id = $_POST['invoice']
How would I write an if statement to check to see if the number that user entered is in that array
I have tried doing in a for each loop
foreach($result as $value){
if($value == $id){
echo 'this';
}else{
continue;
}
is there a better way of doing this?
if (in_array($id, $results)) {
// ...
}
http://php.net/manual/en/function.in-array.php
Use in_array():
if (in_array($_POST['invoice'], $your_array)) {
... it's present
}
ok you can try this:
if ( in_array($id, $results))
{
// execute success
}
else
{
// execute fail
}
You can use in_array, like the others have suggested
if(in_array($id,$results)) {
//do something
} else {
$no_invoice = true;
}
but if you happen to want to use your array key for anything, you can kill two birds with one stone.
if($key = array_search($id,$results,true)) {
echo 'You chose ' . $results[$key] . '<br />';
}
Obviously for echoing you don't need my method - you could just echo $id - but it's useful for other stuff. Like maybe if you had a multi-dimensional array and element [0]'s elements matched up with element[1]'s elements.
If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:
if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}
if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);
for($ac=0; $ac<$arr; $ac++){
if($r[$ac]==$anr[$ac]){
$res=$res+5;
}
}
echo $res;
}
Not quite.
your way is good enough, it only needs to be corrected.
foreach($results as $value){
if($value == $id){
echo 'this';
break;
}
}
is what you really wanted
Related
I have this array of objects:
$table=[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}];
I want to get the value of id_f of each object and check if this value exist in another array ,I tried with this but it gives me the wrong result:
foreach($table as $t){
if (in_array($t[$id_f],$array){
//dosomething}
}else{
//do something else
}
}
I also tried with this:
foreach($table as $t){
if (in_array($t->$id_f,$array){
//dosomething}
}else{
//do something else
}
}
I can't get the right result , I will appreciate any help.
Another approach without foreach loop:
<?php
$table=json_decode('[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]');
$data = [10, 20, 2255];
array_walk($table, function($obj) use (&$data) {
if (in_array($obj->id_f, $data)) {
echo "+";
} else {
echo "-";
}
});
The output obviously is:
+-
You dont show a json_decode() anywhere in your code, thats the first thing to do with a JSON String, to decode it into a PHP data structure. In this case an array of objects.
$other_array = array('2255', '9999');
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$array = json_decode($table);
foreach ( $array as $obj ) {
if (in_array($obj->id_f, $other_array)) {
echo 'Found one ' . $obj->id_f . PHP_EOL;
} else {
echo 'No match for ' . $obj->id_f . PHP_EOL;
}
}
Results
Found one 2255
No match for 5886
There's no need for the dollar sign before your Object property name (actually, it won't work, except of course if $id_f is a real variable which has for value 'id_f', but somehow I doubt it) :
foreach ($table as $t) {
if (in_array($t->id_f, $array){
// do something
} else {
// do something else
}
}
it can be done like this:
to define the object array you can define like below with json string approach. or to define object is like this $table = new stdClass();
<?php
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$obj = json_decode($table);
$array=array("2555","2255");
foreach($obj as $t){
if (in_array($t->id_f,$array)){
//dosomething
}else{
//do something else
}
}
?>
I have an array. Inside that array my Fruit_Name could either be Pear or Apple depending on the button i select in the previous page. Lets say i select Apple the if statement does not seem to work however it does echo. It echos$FruitType and it seems to get Apple which should fire up my if statement and show me "You did it!", but my if condition doesn't. What am i doing wrong?
Array
Fruit_Name=Apple
My Function
function GetField($arr, $field)
{
$result = ' ';
foreach($arr as $line)
{
if (explode('=', $line) [0] == $field)
{
$result = explode('=', $line) [1];
}
}
return $result;
}
$FruitType= GetField($array, 'Fruit_Name');
echo $FruitType;
if ($FruitType == "Apple")
{
echo "You did it!";
}
else if ($FruitType == "Pear")
{
echo "Its not Pear!";
}
When comparing strings (and really, you should do this with any data type) in php, you must use the === notation. The == is only used for numbers, and when used on strings leads to problems like the one you're facing.
So your code should be
If ( $FruitType === "Apple" )
And the Getfield function is incorrect, as mentioned and explained by Dagon.
I'm trying to link the MySQL while loop into foreach loop using something like this :
if($something == true){
foreach($array as $arr){
} else {
while($row = mysql_fetch_array($mysql_query)){
}
// loop instructions
}
It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database
I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :
if($something == true){
$mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
$mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}
while($row = mysql_fetch_array($mysql_query)){
...
That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop
P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above
Put your processing into a function:
function process_data($data) {
// do stuff
}
if($something){
foreach($array as $arr){
process_data($arr);
}
} else {
while($row = mysql_fetch_array($mysql_query)){
process_data($row);
}
}
The other answers here are fine, but you'd be better served just to make sure that $array is a valid array regardless of something ... How about
if (!something){
$array = array();
while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}
foreach($array as $arr){
// do work
}
You'd probably get a better answer if you expanded the scope of what you've explained a bit. Without knowing what the something is and what the data is, plus the ultimate objective then it's hard to tell what kind of structure you should be using.
It seems to me that you could achieve this by just using a function, if the code inside the loop is the same. Like this:
if($something == true)
{
foreach($array as $arr)
{
doWork($arr);
}
}
else
{
while($row = mysql_fetch_array($mysql_query))
{
doWork($row);
}
}
function doWork($arr)
{
//...
}
You cannot nest loop instructions inside a loop like this. You'll need to have two separate loops completely inside the IF statements.
if($something == true){
foreach($array as $arr){
// do work
}
} else {
while($row = mysql_fetch_array($mysql_query)){
// do work
}
}
Maybe you could look at from this viewpoint. And take note that this code uses mysql_fetch_assoc() instead of mysql_fetch_array(). Try both functions and look at the resulting rows with var_dump(). You will see that mysql_fetch_array() has twice as much data. You may want that, but probably not.
if ($something !== true)
{
$array = array();
while($row = mysql_fetch_assoc($mysql_query_result_resource))
{
$array[] = $row;
}
}
foreach($array as $arr)
{
/* PROCESS */
}
Hi I have a PHP array with a variable number of keys (keys are 0,1,2,3,4.. etc)
I want to process the first value differently, and then the rest of the values the same.
What's the best way to do this?
$first = array_shift($array);
// do something with $first
foreach ($array as $key => $value) {
// do something with $key and $value
}
I would do this:
$firstDone = FALSE;
foreach ($array as $value) {
if (!$firstDone) {
// Process first value here
$firstDone = TRUE;
} else {
// Process other values here
}
}
...but whether that is the best way is debatable. I would use foreach over any other method, because then it does not matter what the keys are.
Here is one way:
$first = true;
foreach($array as $key => $value) {
if ($first) {
// something different
$first = false;
}
else {
// regular logic
}
}
$i = 0;
foreach($ur_array as $key => $val) {
if($i == 0) {
//first index
}
else {
//do something else
}
$i++;
}
I would do it like this if you're sure the array contains at least one entry:
processFirst($myArray[0]);
for ($i=1; $i<count($myArray); $1++)
{
processRest($myArray[$i]);
}
Otherwise you'll need to test this before processing the first element
I've made you a function!
function arrayCallback(&$array) {
$callbacks = func_get_args(); // get all arguments
array_shift($callbacks); // remove first element, we only want the callbacks
$callbackindex = 0;
foreach($array as $value) {
// call callback
$callbacks[$callbackindex]($value);
// make sure it keeps using last callback in case the array is bigger than the amount of callbacks
if(count($callbacks) > $callbackindex + 1) {
$callbackindex++;
}
}
}
If you call this function, it accepts an array and infinite callback arguments. When the array is bigger than the amount of supplied functions, it stays at the last function.
You can simply call it like this:
arrayCallback($array, function($value) {
print 'callback one: ' . $value;
}, function($value) {
print 'callback two: ' . $value;
});
EDIT
If you wish to avoid using a function like this, feel free to pick any of the other correct answers. It's just what you prefer really. If you're repeatedly are planning to loop through one or multiple arrays with different callbacks I suggest to use a function to re-use code. (I'm an optimisation freak)
Here's the problem:
I have words I entered via a textarea. I put each word in an entry. i.e words are in an array. On the other hand, I got a wordlist, in which words are separated by newline, I put each word in another array, too.
Now I want to check if $words_entered[$i] = any (and which) of the array $wordlist.
Thanks in advance!
If you want the results in the list:
$intersection = array_intersect($words_entered,explode("\n",$wordlist));
If you want the results NOT in the list:
$diff = array_diff($words_entered,explode("\n",$wordlist));
Use the in_array function:
if (in_array($words_entered[$i], $wordlist))
{
echo 'The word ' . $words_entered[$i] . ' is in the wordlist' . '<br />';
}
I would check on-the fly...
$dic=explode("\n",file_get_contents('dictionary.txt'));
$words=array();
$words=explode(" ",strtolower(file_get_contents('text.txt'));
foreach($words as $index=>$word) {
if(in_array($word,$dic)) {
// do something
} else {
// do something else
}
}
if the text is huge i would speed up the comparison by replacing in_array with isset like this...
$dic_temp=explode("\n",file_get_contents('dictionary.txt'));
$dic=array();
foreach($dic_temp as $k=>$v) {
$dic[$k]=1;
}
unset($dic_temp);
$words=array();
$words=explode(" ",strtolower(file_get_contents('text.txt'));
foreach($words as $index=>$word) {
if(isset($dic[$word])) {
// do something
} else {
// do something else
}
}