More than two variables in a foreach loop - php

I need some information regarding whether or not we can put more than two variable in a foreach loop. Do keep in mind I'm still a complete newbie :D
For example, I'm getting the data of the variable from a database with comma's
<?php
while($segment = $results->fetchRow()) {
$seg = explode(',', $segment['name']);
$section = explode(',', $segment['sek_id']);
$array = array_combine($seg, $section);
foreach($array as $out => $key){
if($out != ""){
?>
<option value="<?php echo $key; ?>"><?php echo $out; ?></option>
and here I managed to put two variables into my foreach loop.
Is there any way with it while still using a foreach loop? Like maybe if I have an 'id=""' where I would put the id's that is in comma's in it?

You can use following way.
<?php
$results = $results->fetchRow();
foreach($results as $result)
{
if(!empty($result['name']))
{
?>
<option value="<?php echo $result['sek_id']; ?>">
<?php echo $result['name']; ?>
</option>
<?php
}
}
<?php
That will be great if you can provide result of $results->fetchRow();
Let me know in case of any query.

Related

Display contents of $_POST one bye one

Hello I am submitting a form with POST method and I want its contents to be echo'ed one by one apart from the last one. So far I am using
<?php foreach($_POST as $data){
echo $data;
}
?>
which displays the whole array of $_POST, how can I make it using common "for" loop to not echo the last item of the array? It doesnt seem to work
<?php
$length=count($_POST)-1;
for($i=0; $i<$length; $i++) {
echo $_POST[$i];
?>
<br>
<?php } ?>
I am getting 5 errors, undefined offset 0 through 4 where the echo line is present
Do the following:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $value;
}?>
<br><?php
} ?>
Your loop for just get numerical index like $_POSR[0], $_POST[1]... This just would work if in the HTML the attribute name of the input elements be numerical also, like name="0" and so on.
foreach perform loop on array independently of index, numerical or string.
Try this:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $index => $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $index . ": " . $value;
}?>
<br><?php
} ?>
ok now I get it, I didnt know the difference between associative and numeric arrays. I fixed it with an if statement

using foreach multiple times

How can I use foreach multiple times?
<?php
$query = $db->query('SELECT tbl_stok.id_stok,
tbl_stok.id_provinsi,
tbl_stok.id_kabupaten,
tbl_stok.tanggal,
tbl_stok.mie_instan,
tbl_stok.beras,
tbl_stok.telur
FROM `tbl_stok` INNER JOIN tbl_wilayah ON tbl_stok.id_provinsi = tbl_wilayah.id_user
');
$query->fetchAll;
?>
I want to use the first foreach to show the data tables:
<?php foreach($query as $row){
echo $row['beras'];
}?>
Then I want to use the second foreach for chart:
<?php foreach($query as $row){
echo $row['telur'];
}?>
However, this foreach works only once.
You can do this:
1) save your data to an array.
foreach($query as $row){
$data[]= $row;
}
2) use your array in every loop you want as many time you want
foreach($data as $row){
echo $row['beras'];
}
foreach($data as $row){
echo $row['telur'];
}
Use foreach only once and store all values you need, like this:
<?php
$beras_array = array();
$telur_array = array();
foreach($query as $row){
$beras_array[] = $row['beras'];
$telur_array[] = $row['telur'];
}
//you can use `for` explained later instead of two `foreach`
foreach($beras_array as $b){
echo $b;
}
foreach($telur_array as $t){
echo $t;
}
//With this method you can also use only one for instead of two foreach
$limit = count($beras_array);
for($i=0; $i<$limit; $i++){
echo $beras_array[$i];
echo $telur_array[$i];
}
?>
I hope it helps

Array returns "Array"

This is my first time trying to create an array but it's not going so well.
My code scans every $_POST in a form when pressing a submit button below an input field. What I wanted it to do was to only fetch the content of a "filled" input. Well life's full of disappointments so then I tried to remove all the empty array elements. But instead of doing that, it echos the word "Array".
I've always been bad at arrays, ever since my C# days and I've never known why because they always look so simple. If anybody can tell me what I'm doing wrong, I'd appreciate it.
PHP code that goes above the <html>
<?php
//This is what I've tried before
//$klant = array();
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord') {
$id = substr($k,10);
$klant[] = $v;
$klant = array_filter($klant);
echo $klant;
}
}
?>
Markup
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<?php
$query = ("select * from table1");
$result = mysqli_query($con, $query) or die (mysqli_error());
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row['rowid'];
?>
<tr><!--There are multiple rows, that's why I'm using foreach($_POST as $k => $v)-->
<td>
<input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" />
<a href="?record=<?php echo $id; ?>">
<button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button>
</a>
</td>
</tr>
<?php } ?>
</table>
</form>
You cannot echo arrays use print_r or var_dump
for Pretty-printing arrays try this
echo "<pre>";
print_r($your_array);
echo "</pre>";
I believe this is what you want!
<?php
$klant = array();
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord' && trim($v)) {
$id = substr($k,10);
$klant[$id] = $v;
}
}
echo "<pre>";var_dump($klant);echo "</pre>";
?>
But I am not that confident that I understand the question clearly. Can you clarify a bit more than this(if this is not what you desire)?
Change this :
echo $klant;
To this :
print_r($klant);
Or this :
var_dump($klant);
echo is just for strings, print_r and var_dump will echo anything (strings, arrays, objects etc).
EDIT for OP EDIT :
This will remove anything that is empty inside the array :
foreach ($klant as $key => $value)
if (empty($value))
unset($klant[$key]);
print_r($klant);
Try this
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord') {
$id = substr($k,10);
$klant[] = $v;
}
}
var_dump($klant);

multiple select in 2 dimensional array in php

In PHP, I am having 2 array
$ex1 = array(a,b,c,d,e,f,g,h);
$ex2 = array(c,e,f);
Here how can I integrate this with multiple select option in PHP page
Here ex1 is the multiple select array like
<select multiple name=slt[]>
</select>
And ex2 values are the chosen listing options
Something like:
<?php
$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');
echo "<select multiple name=slt[]>";
foreach($ex1 as $val){
//in_array() checks if value from 1st array ($val) is present
//anywhere in the second array ($ex2)
//if yes, that option will be selected. I'm using ternary operator
//here instead of if statement
$selected = (in_array($val,$ex2))?' selected':'';
echo "<option value='".$val."'$selected>".$val."</option>";
}
echo "</select>";
?>
PHP Demo
Output Fiddle
I'm not sure about what you want to do, but here's an idea :
$ex1 = array("a","b","c","d","e","f","g","h");
echo "<select multiple>";
foreach( $ex1 as $value ){
echo "<option value='$value'>$value</option>";
}
echo "</select>";
Try running it:
<?php
$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');
?>
<select multiple name=slt[]>
<?php
foreach ($ex1 as $option) {
$active = false;
foreach($ex2 as $selected){
if($option == $selected){
$active = true;
}
}
?>
<option value="<?php echo $option; ?>" <?php if($active===true) echo "selected"; ?>><?php echo $option; ?></option>
<?php
}
?>
</select>

array of data in a drop down menu

I am trying to get the area table of my database to display in a drop down menu but I am having trouble because it is an array.
In my controller I have: $data['city'] = $this->location->fetchCity();
but in my view when I go <?php echo $city; ?> I get this Array why?
Model:
public function fetchCity(){
$this->db->select('area');
$this->db->from('suburbs');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$row = $query->result();
}
Update:
<select>
<?php foreach ($city as $key => $row): ?>
<option value="<?php echo $row['area'];?>"><?php echo $row['area'];?></option>
<?php endforeach; ?>
</select>
<?php echo $city[$key]; ?>
OR
<?php echo $city['area']; ?>
Since your function call returns an Array, this is how I suggest you print it out.
foreach ($city as $key=>$row)
{
echo $row->area;
}
Since your result is an Array of Objects, I'm sure this will get things right.

Categories