If condition equal to array value - php

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.

Related

How can I repeat a specific iteration in a foreach loop in PHP?

As there is no iterator in PHP, the only way to loop through an array without getting the length of the array is to use foreach loop.
Let say I have the following loop:
foreach ($testing_array as $testing_entry) {
$result = my_testing_api_call($testing_entry);
if ($result == 'server dead')
break;
else if ($result == 'done') {
// do something to handle success code
continue;
}
else {
sleep(5);
// I want to retry my_testing_api_call with current $testing entry, but don't know what to write
}
}
One way to do that is to use for loop instead.
for ( $i=0; $i < count($testing_array); $i++ ) {
$result = my_testing_api_call($testing_entry[$i]);
if ($result == 'server dead')
break;
else if ($result == 'done') {
// do something to handle success code
continue;
}
else {
sleep(5);
$i--; //so it will repeat the current iteration.
}
}
The problem is that the $testing_array is not originally using number as index, so I have to do some data massage to use a for loop. Is there a way I can repeat a specific iteration in a foreach loop?
Perhaps a do-while will work for you.
Untested Code:
foreach ($testing_array as $testing_entry) {
do {
$result = my_testing_api_call($testing_entry);
if ($result == 'server dead') {
break 2; // break both loops
} elseif ($result == 'done') {
// do something to handle success code
} else {
sleep(5);
// I want to retry my_testing_api_call with current $testing entry, but don't know what to write
}
} while ($result !== 'done');
}
Or a single loop structure that destroys the input array as it iterates.
Untested Code:
$result = '';
while ($testing_array && $result !== 'server dead') {
$result = my_testing_api_call(current($testing_array));
if ($result == 'done') {
// do something to handle success code
array_shift($testing_array);
} elseif ($result !== 'server dead') {
sleep(5); // I want to retry my_testing_api_call with current $testing entry, but don't know what to write
}
}
Or you can use your for loop by indexing $test_array with array_values() if you don't need the keys in your // do something.
$testing_array = array_values($testing_array);
for ($i=0, $count=count($testing_array); $i < $count; ++$i) {
$result = my_testing_api_call($testing_entry[$i]);
if ($result == 'server dead') {
break;
} else if ($result == 'done') {
// do something to handle success code
} else {
sleep(5);
--$i; //so it will repeat the current iteration.
}
}
If you do need the keys down script, but you want to use for, you could store an indexed array of keys which would allow you to use $i to access the keys and maintain data synchronicity.
My final suggestion:
Use while (key($testing_array) !== null) {...} to move the pointer without destroying elements.
Code: (Demo)
$array1 = [
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
];
while (key($array1)!==null) { // check if the internal pointer points beyond the end of the elements list or the array is empty
$current = current($array1);
$key = key($array1);
echo "$key => $current\n"; // display current key value pair
if ($current < 3) { // an arbitrary condition
echo "\t";
$array1[$key] = ++$current; // increment the current value
} else { // current value is satisfactory
echo "\t(advance pointer)\n";
next($array1); // move pointer
}
}
Output:
one => 1
one => 2
one => 3
(advance pointer)
two => 2
two => 3
(advance pointer)
three => 3
(advance pointer)
four => 4
(advance pointer)
You are trying to handle two different things in your loop, that makes it hard to write clean control flow. You could separate the retry-logic from the result handling:
function call_api_with_retry($entry) {
do {
if (is_defined($result)) sleep(5);
$result = my_testing_api_call($entry);
} while ($result != 'done' && $result != 'server dead');
return $result;
}
foreach ($testing_array as $testing_entry) {
$result = call_api_with_retry($testing_entry);
if ($result == 'server dead')
break;
else if ($result == 'done') {
// do something to handle success code
continue;
}
}
(there might be syntax errors, it's been a while since I wrote PHP code)
To repeat a single specific iteration you need to add a control mechanism, it is not an intended behavior after all.
There are many suggestions here, all of them are kinda over-engineered.
PHP is a high level derivate of C and both languages have the 'goto' operator, it has a bad reputation because people have historically used it too much.
In the end a foreach/while loop is internally nothing else than a 'goto' operation.
Here is the code:
foreach ($array as $key => $value)
{
restart:
if ($value === 12345) goto restart;
}
That's how this should be done just keep in mind that this can cause an endless loop, like in the example.
Look at the next complicated version without goto:
foreach ($array as $key => $value) while(1)
{
if ($value === 12345) continue;
break;
}
This is essentially the same as the goto, just with more code.
If you'd want to "break" or "continue" the foreach loop you'd write "break 2" or "continue 2"

differentiating between two different JSON objects using php

I'am creating a search engine.In this search engine we search movies by actor's name . Searching movies through actor's name returns two different types of JSON data . If the actor name is not found then the JSON is returned in the following format (see the http://netflixroulette.net/api/api.php?actor=)
{"errorcode":404,"message":"Sorry! We couldn't find any movies with that actor!"}
and when the actor name is found the JSON returned is multidimensional and is in the following format.(see the link:http://netflixroulette.net/api/api.php?actor=Yuki%20Kaji)
[{"unit":883,"show_id":70299043,"show_title":"Attack on Titan","release_year":"2013","rating":"4.6","category":"Anime","show_cast":"Yuki Kaji, Yui Ishikawa, Marina Inoue, Daisuke Ono, Hiro Shimono, Hiroshi Kamiya, Keiji Fujiwara, Kish\u00f4 Taniyama, Romi Park, Ryota Ohsaka","director":"","summary":"For over a century, people have been living behind barricades to block out the giant Titans that threaten to destroy the human race. When a Titan destroys his hometown, young Eren Yeager becomes determined to fight back.","poster":"http:\/\/netflixroulette.net\/api\/posters\/70299043.jpg","mediatype":1,"runtime":"24 min"}, { "unit":17256,"show_id":80009097,"show_title":"Magi","release_year":"2012","rating":"3.8","category":"TV Shows","show_cast":"Kaori Ishihara, Erica Mendez, Yuki Kaji, Erik Scott Kimerer, Haruka Tomatsu, Cristina Valenzuela, Daisuke Ono, Matthew Mercer, Takahiro Sakurai, Lucien Dodge","director":"","summary":"A land of mysterious ruins and a magical treasure hunt await young Aladdin and his courageous friend Alibaba for the adventure of their lives.","poster":"http:\/\/netflixroulette.net\/api\/posters\/80009097.jpg","mediatype":0,"runtime":"N\/A"}]
I've tried this code
$output = json_decode($output);
if($output['errorcode']==400)
{
foreach($output as $key =>$row)
{
echo "<p>$key : $row";
echo '<br>';
}
}
else
{
foreach($output as $value)
{
foreach($value as $key =>$row)
{
if($key == "mediatype" || $key == "runtime" || $key == "unit" || $key == "show_id" )
continue;
else if($key == "show_cast" )
{
echo"<br>Show Cast:";
$pieces = explode(",", $row);
foreach($pieces as $strings)
{
$link='http://localhost:8000/?Title=&director=&Actor='.$strings;
echo "<li><a href='$link'>$strings</a>";
}
echo "<br>";
}
else if($key == "director" )
{
if(empty($row))
echo"<br>Director:No details of director<br>";
else
{
echo"<br>Director:";
$link='http://localhost:8000/?Title=&director='.$row.'&Actor=';
echo "<a href='$link'>$row</a><br>";
}
}
else if($key !="poster")
{
echo "$key : $row";
echo '<br>';
}
else
{
echo '<img src="'.$row.'" />';
}
}
echo "<br><br><br><br><br><br>";
}
}
Using this gives me error of "Undefined index: errorcode" . Basically my question is what to use in if-else condition to differentiate between the two received JSON objects that are recieved.
Please help!! Thanks in advance..
Try if(is_object($output) && isset($output->errorcode)).
So it would be like this:
$output = json_decode($output);
if(is_object($output) && isset($output->errorcode))
{
foreach($output as $key =>$row)
{
echo "<p>$key : $row";
echo '<br>';
}
}
else
{
// the rest
}
What's happening is the json is an object when there are no matches, but it is an array of objects when there are matches.
If we just use if(isset($output->errorcode)), then, in the case where there are matches, $output is an array and not an object, and the above attempts to treat it like an object, resulting in an alert about treating an array like an object.
The boolean && will "short circuit" when the first condition is false, and it will never evaluate the second condition. So we first check to see if it is an object with is_object().. if it isn't, then it will never check to see if it has a member called "errorcode", dodging the alert about treating an array as an object.

PHP How to add an array inside another array with the same key name rather than replacing the one that exists currently

I know my question is kind of confusing, and also similar to others. But it is a tad different in a few ways.
Basically I have this multi dimensional array in PHP with like 6 "dimensions".
I'm building, let's call it $array1, up from a whole bunch of values, which are all stored in a different array, which we will call $array2. $array2 is organized in a way that when you map it out over 6 array levels it makes sense. so an example of how I would create a value in $array1 from $array2 would be:
$array1[$array2[val1][val2]][$array2[val3][val4]] = $array2[val4][val5];
So we are adding in a value to $array1 one string at a time.
The problem I am having is that, $array2 isn't always organized by subject.
So for example (i will use food) $array2 will have as it's values
fruit
green
apple
grape
cereal
corn
wheeties
fruit
blue
blueberries
I used some spacing in order to read it better
so when fruit comes in the second time, it overrides the first fruit inputted. Instead I would like to merge them so $array1 will look like
fruit
green
apple
grape
blue
blueberries
cereal
corn
wheeties
Updated Code:
for($r = 0; $r<=$splitUpLength; $r++) {
if($r == 0) {
if ($splitUp[$r]==$p[$main][$cat1]) {
} else {
$cat1++;
$p[$main][$cat1] = $splitUp[$r];
//echo $p[$main][$cat1];
//echo "<br>";
}
}
if ($r == 1) {
$main++;
if ($splitUp[$r] == $p[$main][$cat2]) {
} else {
$cat2++;
$p[$main][$cat2] = $splitUp[$r];
//echo "-".$p[$main][$cat2];
//echo "<br>";
if (strpos($p[$main][$cat2],'-') !== false) {
$realFoods[$p[$main-1][$cat1]] = $p[$main][$cat2];
continue;
}
}
}
if ($r == 2) {
$main++;
if ($splitUp[$r] == $p[$main][$cat3]) {
} else {
$cat3++;
$p[$main][$cat3] = $splitUp[$r];
//echo "--".$p[$main][$cat3];
//echo "<br>";
if (strpos($p[$main][$cat3],'-') !== false) {
$realFoods[$p[$main-2][$cat1]][$p[$main-1][$cat2]] = $p[$main][$cat3];
continue;
}
}
}
if ($r == 3) {
$main++;
if ($splitUp[$r] == $p[$main][$cat4]) {
} else {
$cat4++;
$p[$main][$cat4] = $splitUp[$r];
//echo "---".$p[$main][$cat4];
//echo "<br>";
if (strpos($p[$main][$cat4],'-') !== false) {
$realFoods[$p[$main-3][$cat1]][$p[$main-2][$cat2]][$p[$main-1][$cat3]] = $p[$main][$cat4];
continue;
}
}
}
if ($r == 4) {
$main++;
if ($splitUp[$r] == $p[$main][$cat5]) {
} else {
$cat5++;
$p[$main][$cat5] = $splitUp[$r];
//echo "----".$p[$main][$cat5];
//echo "<br>";
if (strpos($p[$main][$cat5],'-') !== false) {
$realFoods[$p[$main-4][$cat1]][$p[$main-3][$cat2]][$p[$main-2][$cat3]][$p[$main-1][$cat4]] = $p[$main][$cat5];
continue;
}
}
}
if ($r == 5) {
$main++;
if ($splitUp[$r] == $p[$main][$cat6]) {
} else {
$cat6++;
$p[$main][$cat6] = $splitUp[$r];
//echo "-----".$p[$main][$cat6];
//echo "<br>";
if (strpos($p[$main][$cat6],'-') !== false) {
$realFoods[$p[$main-5][$cat1]][$p[$main-4][$cat2]][$p[$main-3][$cat3]][$p[$main-2][$cat4]][$p[$main-1][$cat5]] = $p[$main][$cat6];
continue;
}
}
}
}
$main=0;
$h++;
//echo $h." ";
}
}
So obviously it's a lot
I'm basically splitting up pieces of data and storing them in the $p array. the data is being split up by catagory, and the actual data piece will look like this:
Babyfood, cereal, rice, with mixed fruit, junior - 100 g (100 g)
So i'm splitting them up by "," and once a "-" is detected, it loads all the relevant info into the main array $realFoods
Because some catagores in the data come up twice, like cereal might come up twice, it replaces the already added cereal items. Instead of replacing, I would like to add everything into that cereal category/ array
decleration of the variables:
$h = 0;
$p = array();
$main=0;
$cat1=0;
$cat2=0;
$cat3=0;
$cat4=0;
$cat5=0;
$cat6=0;
$realFoods=array();
I've been looking a lot. and here is a smaller version of my question:
PHP - Merge duplicate array keys in a multidimensional array
But I need to blow that up to support a lot of dimensions. and I just wouldn't know where to begin :/
Try this function to merge and keep your key "subject" array:
http://php.net/manual/en/function.array-merge-recursive.php
By the way PHP will try each element of array and merge than

PHP If statements and Arrays

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

PHP Array foreach question

I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}

Categories