I have a bellow php while and for loop.
In while loop it's storing $ch_for data in $ch_for array.
Using print_r this array is showing these value :
Array ( [ch7] => Seven [ch8] => Eight )
And trying to access this array data in for loop using this line :
echo $ch_for["ch{$x}"];
But it's showing an error message : Illegal string offset 'ch7' in
...
While and For Loop
$ch_for = array();
$ch_name = array();
while ( $fetchChannel = mysqli_fetch_array($getChannel) ) {
$ch_id = (int) $fetchChannel['ch_id'];
$ch_for[$fetchChannel['ch_name']] = htmlspecialchars($fetchChannel['ch_for']);
$ch_name[] = htmlspecialchars($fetchChannel['ch_name']);
}
for ($x=1; $x<=12; $x++) {
if( in_array('ch'.$x, $ch_name)) {
$sel = 'checked = "checked" ';
echo $ch_for["ch{$x}"];
} else {
$sel = '';
$ch_for = '';
}
?>
<div class="checkbox form-inline">
<label><input <?php echo $sel; ?> type="checkbox" name="ch_name[]" value="ch<?php echo $x; ?>">CH<?php echo $x; ?></label>
<input type="text" name="ch_for[]" value="<?php echo $ch_for; ?>" placeholder="Channel details" class="form-control ch_for">
</div>
<?php
}
Result of var_dump(array_keys($ch_for));
array(2) {
[0]=>
string(3) "ch7"
[1]=>
string(3) "ch8"
}
Your array is associative array.SO use in_array() in array_keys.Like this..
<?php
$array = array('ch7'=>'Seven','ch8'=>'Eight');
$keys = array_keys($array);
//print_r($keys);
for ($x=1; $x<=12; $x++) {
if( in_array('ch'.$x,$keys)) {
$sel = 'checked = "checked" ';
echo $array["ch{$x}"].PHP_EOL;
} else {
$sel = '';
$ch_for = '';
}
}
?>
Output:
Seven
Eight
You're overwriting $ch_for in your else-branch since the first key is ch7, hence the first loop (ch1 is not in $ch_name and thus triggers the else) overwrites $ch_for.
Related
i have arrays like :
foreach($Pics AS $Allpics) {
print $Allpics;
}
Result my values:
string(40) "760_e7c5c3202c778318fdf92f406da31742.jpg"
string(40) "760_00f500b6398b4d8a0cde299730f57148.gif"
string(40) "760_54b1bb6895b636f45c56911be4f67c11.png"
string(40) "760_05986e1f46651698a8aa4f8ed17ab070.jpg"
i need Split array values into two columns !
like :
[column 1] [column 2]
760_e7c5c3202c778318fdf92f406da31742.jpg 760_54b1bb6895b636f45c56911be4f67c11.png
760_00f500b6398b4d8a0cde299730f57148.gif 760_05986e1f46651698a8aa4f8ed17ab070.jpg
Html Result like :
<div class='row'>
<div class='col-sm-6'>
760_e7c5c3202c778318fdf92f406da31742.jpg
760_54b1bb6895b636f45c56911be4f67c11.png
</div>
<div class='col-sm-6'>
760_00f500b6398b4d8a0cde299730f57148.gif
760_05986e1f46651698a8aa4f8ed17ab070.jpg
</div>
</div>
thanks for your help my friends!
You can do with array_chunk() but the problem is, if records is odd then array_chunk() create third array so, you miss last record.
It's very simple....
Use array_slice() to avoid logical error.
$Allpics = array("nature", "trees", "beauty","funny", "fun");
//counting number of records
$countRecords = count($Allpics);
//dividing array in to two array
$col1 = array_slice($Allpics, 0, $countRecords/2 + 0.5);
$col2 = array_slice($Allpics, $countRecords/2 + 0.5, $countRecords);
//making two columns
$row = array("column 1" => $col1, "column 2" => $col2);
print_r($row);
//Output
Array(
[column1] => Array(
[0] => nature
[1] => trees
[2] => beauty
) [column2] => Array(
[0] => funny
[1] => fun
)
)
This code will create two columns, records are odd so, 1st column contain 3 records and 2nd column contain 2 records. If the records are even then it will create two equal columns.
If you want same array keys from $Allpics then use true in array_slice()
Read more at http://php.net/manual/en/function.array-slice.php
use array_chunk()
array_chunk($arrays,2);
Please see the code, it may help you to achieve your goal
$arrays = array('Like' ,'Starts' , 'Moons', 'Skys');
$odd = array();
$even = array();
$i=1;
foreach($arrays as $val)
{
if($i%2==0)
$even[] = $val;
else
$odd[] = $val;
$i++;
}
print_r($odd);
print_r($even);
Use array chunks...
$arrays = ["Like" ,"Starts" , "Moons", "Skys"];
$arrays = array_chunk($arrays,2);
<div class='row'>
<div class='col-sm-6'>
<?php foreach ($arrays[0] as $key => $value) {
echo $value."<br>";
} ?>
</div>
<div class='col-sm-6'>
<?php foreach ($arrays[1] as $key1 => $value1) {
echo $value1."<br>";
} ?>
</div>
</div>
Here you can specify the column count and the algorithm will do the rest
echo "<div class='row'>";
// cant be greater than 12 because bootstrap only supp 12 columns
$columns = 2;
$arrays = array('Like' ,'Starts' , 'Moons', 'Skys');
$array_m = round(count($arrays) / $columns);
for ($i = 0; $i < $columns; $i++){
echo "<div class='col-sm-".round(12/$columns)."'>";
for ($i2= $i * $array_m; $i2 < ($i+1==$columns? count($arrays) : $array_m) ; $i2++) {
echo $arrays[$i2] . '<br>';
}
echo "</div>";
}
echo "</div>";
Please try this code
$arrays = array('Like' ,'Stars' , 'Moons', 'Skys');
$arraychunk=array_chunk($arrays,2);
?>
<div class='row'>
<?php
foreach($arraychunk as $item)
{
?><div class='col-sm-6'><?php
foreach($item as $arr)
{
echo "$arr"."<br>";
}
?></div><?php
}
?>
</div>
I have problem in returning the first key of array in foreach. I can return the $key but i cant figure out on returning the first $key only.
<td>
<div align="center">
<span class="formlist">
<select id="plant" name="plant[]" class="form-control" multiple="multiple">
<?php
$query_plant = "SELECT * FROM plant WHERE plant_enable=1 ORDER BY plant_name";
$rs_plant = DB_Query($query_plant);
while ($row_plant = DB_FetchRow($rs_plant)) {
$plant.='<option name='.$row_plant["plant_shortname"].' value='.$row_plant["plant_id"].'>' .$row_plant["plant_name"].' ['.$row_plant["plant_id"].']</option>';
}
mysql_free_result($rs_plant);
echo $plant;
?>
</select>
</span>
</div>
</td>
if(isset($_POST['plant'])) {
$checkbox1 = $_POST['plant'];
$chk="";
$stf_sql = "SELECT * FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$stf_res = DB_Query($stf_sql);
if(DB_RowsReturned($stf_res) > 0) {
$del_sql = "DELETE FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$del_res = DB_Query($del_sql);
}
foreach($checkbox1 as $chk1)
{
$in_ch="insert into test_plant(staff_id, plant_name, submit_dt) values ('$STAFF_ID','$chk1', Now())";
$in_res = DB_Query($in_ch);
$abc = mysql_query("SELECT * FROM test_plant");
while($abc_row = mysql_fetch_assoc($abc)) {
foreach($abc_row as $key => $value) {
echo $key; //return first key here
}
}
}
} else {
echo "OK";
}
I have tried returning $key[0] but it returns the first letter only. I want to return 'p_id'
Like this,
$keys = array_keys($checkbox1);
print_r($keys); // for all keys
echo $keys[0]; // It will echo first key of the array.
You could reset the internal array pointer and then get the key of the current element:
reset($checkbox1);
echo key($checkbox1);
(Put this outside your outermost while loop).
Or you could even get all the array keys, and then grab the current key:
echo current(array_keys($checkbox1));
I have tried this simple code to generate an array which will send and a form data in post method. what is the way of receiving this array in desired page? Here is the code:
$serial = 0;foreach ($results as $row) {$serial = $serial + 1;
Html:
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
$used_serials = $_POST['serials];
foreach( $used_serials AS &$serial ){
$key = 'question-'.$serial;
$wanted_serial_pack = $_POST[$key];
}
OR better use an multidimensional Array structure like:
name="question['serials'][$serial]"
Then you can loop over $_POST['serials]
PHP
$serial = 0;
$inputs = array();
foreach ($results as $row) {
$serial = $serial + 1;
$inputs[] = "<input name=\"question['keys']['{$serial}'][]\"/>";
}
template.php:
echo implode(' ',$inputs);
Submit.php
$results = $_POST['keys];
foreach($results as $serial_array){
var_dump($serial_array);
}
Something like this may help.
<?php
$i=0;
if( $free_form_fields != '' ) :
foreach ($free_form_fields as $fields)
{
$parameters = json_decode($fields->parameters);
// echo $i;
echo "{$form_field_order[$i]}";
// if($form_field_order[$i] == $fields->id)
// {
echo "<li class='ui-state-default' id={$fields->id}>{$parameters->label}</li>";
// }
$i = $i+1;
}
endif;
?>
I want to check something like this if($form_field_order[$i] == $fields->id)
but it is giving me an error
> Undefined offset: 2
so basically how can i access the $i th value (0,1...) of array $from_field_order?
Edit
print_r($form_field_order);die(); gives an array
Array ( [0] => 2 [1] => 1 )
The array contains only two elements (0,1 indexed). It tries to access index 2 and throws this error as it is not existing. So Put a condition to check if the element exists using isset($form_field_order[$i]) before accessing that
Try this,
<?php
$i=0;
if( count($free_form_fields) > 0 ) :
foreach ($free_form_fields as $fields)
{
$parameters = json_decode($fields->parameters);
// echo $i;
echo $form_field_order[$i];
// if($form_field_order[$i] == $fields->id)
// {
echo "<li class='ui-state-default' id={$fields->id}>{$parameters->label}</li>";
// }
$i = $i+1;
}
endif;
?>
I need to loop through a post array and sumbit it.
#stuff 1
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />
#stuff 2
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />
But I don't know where to start.
This is how you would do it:
foreach( $_POST as $stuff ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing ) {
echo $thing;
}
} else {
echo $stuff;
}
}
This looks after both variables and arrays passed in $_POST.
Likely, you'll also need the values of each form element, such as the value selected from a dropdown or checkbox.
foreach( $_POST as $stuff => $val ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing) {
echo $thing;
}
} else {
echo $stuff;
echo $val;
}
}
for ($i = 0; $i < count($_POST['NAME']); $i++)
{
echo $_POST['NAME'][$i];
}
Or
foreach ($_POST['NAME'] as $value)
{
echo $value;
}
Replace NAME with element name eg stuff or more_stuff
I have adapted the accepted answer and converted it into a function that can do nth arrays and to include the keys of the array.
function LoopThrough($array) {
foreach($array as $key => $val) {
if (is_array($key))
LoopThrough($key);
else
echo "{$key} - {$val} <br>";
}
}
LoopThrough($_POST);
Hope it helps someone.
You can use array_walk_recursive and anonymous function, eg:
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
array_walk_recursive($fruits,function ($item, $key){
echo "$key holds $item <br/>\n";
});
follows this answer version:
array_walk_recursive($_POST,function ($item, $key){
echo "$key holds $item <br/>\n";
});
For some reason I lost my index names using the posted answers. Therefore I had to loop them like this:
foreach($_POST as $i => $stuff) {
var_dump($i);
var_dump($stuff);
echo "<br>";
}