applying rule only once using in_array - php

Hello I was wondering how to do the following as I have been going around without an answer. So I will try to simplify as much as I can.
I have set some values for an associative array
$vNArray ['Brandon'] = $item[3];
$vNArray['Smith']= $item[4];
$vNArray ['Johnson']= $item[5];
$vNArray ['Murphy']= $item[6];
$vNArray ['Lepsky']= $item[7];
foreach ($vNArray as $key => $value){
if(!empty($value)){
$result .= "\t\t\t\t<li><strong>$key</strong>" .$value. "</li>\n";
}
But now I want to target specific values within that array so here is another array:
$display_id=array('Brandon', 'Murphy');
foreach ($vNArray as $key => $value){
if(!empty($value)){
//Looks into the display_id array and renders it differently
if (in_array($key, $display_id)) {
$data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";
} else {
$result .= "\t\t\t\t<li><strong>$key</strong>$value</li>\n";
}
}
The result for the first condition is correct but repeated for both in_array values:
<li id="Brandon Value">Murphy Value</li>
<li id="Brandon Value">Murphy Value</li>
Below is correct:
<li><strong>Smith</strong> Value of Smith</li>
<li><strong>Smith</strong> Value of Johnson</li>
<li><strong>Lepsky</strong> Value of Lepsky</li>
How do I stop it from repeating depending on the number of arrays?

$data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";
You've hardcoded the vNArray keys, so that regardless of which name got matched, you're always outputting the same values. You'd want
$data .= "\t\t<li id=\"{$key}\">{$value}</li>\n";
instead.
There's no need to do the string concatenation as you are. PHP can insert array elements into a string nicely, and it eliminates the need to escape quotes everywhere, which means for hideously ugly code to read through.

Look at your loop carefully.
You're using a foreach loop, which means you are going through the array each time.
Your if(in_array(...)) condition checks to see whether the key is in your $display_id array. That happens twice, for Brandon and Murphy.
When that condition happens twice, $data is appended twice meaning you will get the results displayed twice.
I'm not sure what this helps, but just look at your loops carefully. Can you clarify what you're exactly trying to achieve, or what your desired output is?
Good luck.
EDIT:
I reread your question and realized something -- do you just want your output to print once?
Look into the break syntax. After you append it in the if condition, add a break; and that will break out of the loop printing it once.

Related

foreach $key variable clarification

I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list']) it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list'], $_POST['submit2'] seems to be only used to check if is set and nothing else in your piece of code. What foreach does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key) in your case. So after the loop, $key will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list'] actually an array?
If you're trying to 'glue' together all items of $_POST['check_list'], you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
You are saying that $_POST['check_list'] is an array if implode() works on it, so no need to loop to get individual items. To implode() the values:
echo implode(',', $_POST['check_list']);
To implode() the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach() iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
implode function needs array as second argument. You are passing string value as second argument. That's why it's not working.

Checking the first element of array, regardless of array indexes

I have a need to check if the elements in an array are objects or something else. So far I did it like this:
if((is_object($myArray[0]))) { ... }
However, on occasion situations dictate that the input array does not have indexes that start with zero (or aren't even numeric), therefore asking for $myArray[0] will generate a Notice, but will also return the wrong result in my condition if the first array element actually is an object (but under another index).
The only way I can think of doing here is a foreach loop where I would break out of it right on the first go.
foreach($myArray as $element) {
$areObjects = (is_object($element));
break;
}
if(($areObjects)) { ... }
But I am wondering if there is a faster code than this, because a foreach loop seems unnecessary here.
you can use reset() function to get first index data from array
if(is_object(reset($myArray))){
//do here
}
You could get an array of keys and get the first one:
$keys = array_keys($myArray);
if((is_object($myArray[$keys[0]]))) { ... }
try this
reset($myArray);
$firstElement = current($myArray);
current gets the element in the current index, therefore you should reset the pointer of the array to the first element using reset
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.reset.php

PHP while inside while

Let's say I'm trying to combine items from two lists, and I want to get this result:
A7
A8
B7
B8
This is my code:
<?php
$list1_array = array('A', 'B');
$list2_array = array('7', '8');
while(list( , $item1) = each($list1_array)) {
while(list( , $item2) = each($list2_array)) {
echo $item1.$item2."<br />";
}
}
?>
I get this result:
A7
A8
I seems like outside 'while' doesn't make the second loop?
What am I doing wrong?
While it might be better to use a slightly more common (perhaps more readable) approach (e.g. by using foreach loops as shown by GolezTrol,) in answer to your original questions:
The problem is most likely happening because the internal "cursor" (or "pointer") for your array is not being reset... so it never gets back to the start of the original array.
Instead, what if you try something like this:
<?php
$list1_array = array('A', 'B');
$list2_array = array('7', '8');
while(list(,$item1) = each($list1_array)) {
while(list(,$item2) = each($list2_array)) {
echo $item1.$item2."<br />";
}
reset($list2_array);
}
?>
Why not use foreach?
foreach ($list1_array as $item1)
{
foreach ($list2_array as $item2)
{
echo $item1.$item2."<br />";
}
}
Using a while loop with each makes the loop depend on the array pointer. An array has a pointer that tells you which item is the 'current' one. You can use functions like current to get the current item in the array. each is also such a function. It returns the current item (or actually an array with the key and value of the current item).
And therein lies the problem. The inner while loop stops when you are at the end of the array. So for the first item of the outer array (array1), the inner while loop (array2) runs fine. But the second time, the pointer is still at the end of the array and each returns false right away.
So, the solution could be to reset the array pointer, using the reset function as sharply pointed out by #summea. Or you can use a foreach loop, which is not affected by this fenomenon, because it resets the array pointer itself when it starts. Also, I this it's more readable, especially due to the weird list construct. Nevertheless, it might be good to know how the internals work, and your while loop works more low-level than foreach.

Returning string value in php array

Its a simple problem but i dont remember how to solve it
i have this array:
$this->name = array('Daniel','Leinad','Leonard');
So i make a foreach on it, to return an array
foreach ($this->name as $names){
echo $names[0];
}
It returns
DLL
It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'
try this one :
foreach ($this->name as $names){
echo $names; //Daniel in first iteration
// echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'
}
echo $this->name[0];// gives only 'Daniel' which is the first value of array
Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].
Edit: Maybe it makes sense to use more descriptive names for your variables.
For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.
Additional answer concerning your results :
You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.
Use your iterative element to get the complete string everytime, the alias you created after as.
If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :
http://php.net/manual/fr/control-structures.foreach.php
http://us1.php.net/manual/fr/language.types.array.php

For-Each Loop Misses First Index When Multiple Indices Exist

I've got the below PHP which works great when the array of locations only have 1 value, but when it has any number more than 1, the information on the first location keeps printing out blank. The array is set by calling explode on a comma-delimited list. When I set the array manually immediately before the loop, it works great! Yet not when I use explode, even though I printed the array and can confirm it's getting set up just as I expect (with the correct 0 index). The code I have is:
echo "<ul>";
foreach ($locations as &$value)
{
$locationDetails = mysql_query("SELECT id, name FROM locations WHERE id='$value'");
$locationDetailRow = mysql_fetch_assoc($locationDetails);
echo "<li>".$locationDetailRow['name']."</li>";
}
unset($value);
echo "</ul>";
I've confirmed that the query does not fail, that $value is what I expect it to be, and that the name does exist for the first $value in every case.
Any reason this should be failing on the first case when there are multiple locations?

Categories