PHP foreach loop not reading values from array - php

I have simple PHP array with data from checkbox. I need add values into array and then insert data into database. It works but foreach not infringement parameter.
So i testing with increment:
$arr = array();
array_push($arr, $_POST['chbox']);
and it looks like 123,125 in array (two elements)
Next step is to return number of elements (or values in next step):
$id=0;
foreach( $arr as $row)
{
$id++;
};
and returns $id=1;
if i'm trying read values:
foreach( $arr as $row)
{
$row[$id]
$id++;
};
Return only 123

If you are doing a foreach, $row is the value already.
foreach($arr as $row) {
echo $row;
$id++;
}

In your foreach() loop, $row is just one array value. Not the array. Replace with $arr should solve.
$id = 0;
foreach( $arr as $row ){
echo $arr[$id];
$id++;
}
echo 'Total items: ' . $id; // OR count( $arr );

$arr =array(123,125);
foreach($arr as $arrr):
echo $arrr.',';
endforeach;
Output will be:
123,125,

Just try following
foreach($arr as $row){
echo $row;
};
Edit 1:
Better use var_dump($_POST["chkbox"]) or print_r($_POST["chkbox"]) to see the array you are getting. Then it will be easier for you to decide how to get data.

Related

Combine 2 Arrays In Foreach in PHP

I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.
This is my username list from database.
$digits = [1,2,3,4];
$results = $db->table($usernames)
->where('memberID', $mID)->limit(10)
->getAll();
foreach ($results as $result) {
echo $result->userName;
}
I tried this:
$combined = array_merge($digits, $results);
foreach (array_unique($dogrularVeSiklar) as $single) : { ?>
{
echo $single.'<br>';
echo $results->userName;
},
}
You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:
$combined = array_combine($digits, $results);
foreach ($combined as $digit => $result) {
echo $digit . '<br>' . $result;
}
foreach operates on only one array at a time.
The way your array is structured, you can use array_combine() function to combine them into an array of key-value pairs then foreach that single array

Php - how to store tuples of 3 elements in an array?

I need to store three string values at each iteration of a loop, e.g.
$myArray = array();
foreach (..) {
$myArray[] = // I need to store as a single row or tuple three strings
}
foreach ($myArray as $arrayTuple)
// Do something with $arrayTuple.firstString, $arrayTuple.secondString and $arrayTuple.thirdString
I can't seem to understand how to do this with an associative array.
If I understand correctly then you want like this
$myArray = array();
foreach (..) {
$myArray[] = array("one","two","three");
}
This should helps you, if I understand you correctly:
foreach ($array as $key => $val) {
$myArray[$key] = $val;
}
You can use array_push()
For example:
$myArray = array();
array_push($myArray, "one","two","three");
Or
$myArray = array();
array_push($myArray, "one:two:three");

SELECT array from mysql table and print

I have a column in my table that contain an array like:
1,4,2,8,4,5,7
How to select these numbers and print them separately?
Item: 1
Item: 4
Item: 2
Item: 8
Item: 4
Item: 5
Item: 7
What I have tried:
$result = mysql_query('SELECT * FROM test');
$arr = array();
while(($row = mysql_fetch_array($result))) {
$arr = array_merge($arr , explode(',', $row['item']));
echo "Item: " . $arr . "<br>";
}
Result:
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Can anyone help me?
Your biggest problem is trying to echo the whole array at once rather than echoing an index of the array at a time.
Unless you plan on using all the rows again after the while loop, you don't need the array_merge so take that out. What you need is a foreach inside the while loop to loop through the array created by explode.
while(($row = mysql_fetch_array($result)))
{
$arr = explode(',', $row['item']);
foreach ($arr as $key => $value)
{
echo "Item [$key]: " . $value . "<br>";
}
}
(And you really should switch off of mysql_ to PDO or mysqli_ since mysql_ is deprecated.)
try:
$arr = explode(',', $row['item']);
foreach($arr as $single){
echo "item: $single";
}
You are almost there. I hope this gives the result you expect. In your question it is not quite clear how exactly the data is stored.
If all the data is in one row, this will do it:
$result = mysql_query('SELECT item FROM test');
$arr = array();
$row = mysql_fetch_array($result);
$arr = explode(',', $row['item']);
foreach ($arr as $item) {
echo "Item: " . $item . "<br>";
}

Create multiple span based on array

I have an array that looks like this:
$elm = 'a,b,c';
I need the values of the array so I use explode to get to them:
$q = explode(",",$elm);
I then would like to echo every single item into a span, so I make an array:
$arr = array();
foreach($html->find($q[0]) as $a) {
$arr[] = $a->outertext;
}
$arr2 = array();
foreach($html->find($q[1]) as $b) {
$arr2[] = $b->outertext;
}
$arr3 = array();
foreach($html->find($q[2]) as $c) {
$arr3[] = $c->outertext;
}
And then finally I output like this:
echo "<ul>";
for($i=0; $i<sizeof($arr + $arr2 + $arr3); $i++)
{
echo "<li>";
echo "<span>".$arr[$i]."</span>";
echo "<span>".$arr2[$i]."</span>";
echo "<span>".$arr3[$i]."</span>";
echo "</li>";
}
echo "</ul>";
The problem is that I have to write all the items ($q[0] + $q[1] + $q[2]) and the corresponding span (<span>".$arr[$i]."</span>) This is a problem because in reality I don't know what and how long the first array ($elm) is. Therefore I don't want to 'physically' write down all the span elements but rather create them on the fly depending on the array $elm. I tried many things but I can't figure it out.
The basic issue here is that you don't know how many elements $elm will contain. foreach is the best choice here, as it doesn't require the length of the array to loop through it.
Use a nested foreach loop to store all the outertexts in an array:
foreach (explode(",", $elm) as $elem) {
foreach ($html->find($elem) as $a) {
$arr[$elem][] = $a->outertext;
}
}
$arr[$elem][] is the important bit here. On each iteration of the outer loop, the value of $elem will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a'], $arr['b'] and $arr['c'] and add the outertext values to the respective index.
Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:
echo "<ul>";
foreach ($arr as $sub) {
echo "<li>";
foreach ($sub as $span) {
echo "<span>".$span."</span>";
}
echo "</li>";
}
echo "</ul>";

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Categories