All of array not showing? - php

OK, this is weird. I have an array of time blocks:
$time_block = array("09:00:00-13:00:00","10:00:00-14:00:00");
And I want to loop through them to create a start time and end time for each block:
foreach($time_block as $val)
{
for($x = 0; $x < count($time_block); $x++)
{
$time=$val[$x];
echo substr($time,0,8);
echo "<br>";
echo substr($time,-8);
}
echo "<br>";
echo "<br>";
}
The end result should be:
09:00:00
13:00:00
10:00:00
14:00:00
But I am getting:
0
09
9
1
10
0
Any thoughts?

You wrote: $time = $val[$x];
$val is not an array, it's a string, and seems like you are doing a foreach and then a for on the same array?
You can use something like:
foreach ($timeblock as $timeString) {
list($start, $end) = explode("-", $timeString);
echo "$start $end\n";
}

foreach($time_block as $v) {
print_r(explode( '-',$v ));
echo '<br><br>';
}

In your foreach loop, $val is a string. When you ask for $val[$x], your asking for the xth character of that string. Probably not what you want.
Solution:
Take out the for statement, and change
$time=$val[$x];
to
$time=$val;

Try this:
for($x = 0; $x < count($time_block); $x++){
$time = $time_block[$x];
echo substr($time,0,8);
echo "<br>";
echo substr($time,-8);
echo "<br><br>";
}
You're using 2 nested loops while you only have 1 dimension in your data set. That should make you think.

The problem with your approach is you're trying to loop through the element two times. If you use foreach($time_block as $val), in every iteration $val will be a single element of the array. For example, on the first run, it will store "09:00:00-13:00:00". So in your for loop, you were trying to loop through this $val, which is actually possible as strings can be accessed as arrays (the characters in the string being the elements).
This will produce the exact output you needed:
foreach($time_block as $val) {
$t=explode('-', $val);
echo $t[0]."<br>".$t[1]."<br><br>";
}
Here, explode() is used to separate the time values in $val based on the - character. $t will be an array, holding the two times in $val as its two elements.

In your code you are double looping, just use it like this:
$time_block = array("09:00:00-13:00:00","10:00:00-14:00:00");
foreach($time_block as $time) {
echo substr($time,0,8) . " ";
echo substr($time,-8) . "\n";
}
OUTPUT
09:00:00 13:00:00
10:00:00 14:00:00

Related

Move values after comma to newline to text file

I have values in my database that has values with commas. Eg:
Monday,Tuesday,Wednesday,Thursday,Friday. When I call the row from the database where certain id, I want to write the the result to a text file after every comma into a new line as follows:
Monday
Tuesday
Wednesday
Thursday
Friday
One below the other.
Hope this makes sense.
You can use explode function.
explode — Split a string by string
$days = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday";
$weekdays = explode(",", $days);
foreach( $weekdays as $value ){
echo $value."\n";
}
Output:
Monday
Tuesday
Wednesday
Thursday
Friday
I think it will work for you!
Something like that:
$result = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday";
$array = explode(",", $result);
foreach( $array as $key => $value ){
echo $value."\n";
}
explode function will help you
$str = "Monday,Tuesday,Wednesday,Thursday,Friday";
$val = explode(",",$str);
foreach ($val as $key=>$value) {
echo $value.'</br>';
}
Use something like this
$colVal = $row['col-name'];
echo str_replace(",", "\r\n", $colVal);

Foreach loop and average in PHP

I'm rather new to programming in general. I'm starting off with some exercises but I'm kind of getting stuck. I created an array and looped thru with a foreach loop to print out each individual number stored in the array, but I dont know what to do to find the average of the numbers and print it out.
<?php
$myArray = array(87,75,93,95);
foreach($myArray as $value){
echo "$value <br>";
}
?>
only as an exercise, becuse if you actully wanted to do this you would use #kittykittybangbang's answer
<?php
$myArray = array(87,75,93,95);
$sum='';//create our variable
foreach($myArray as $value){
$sum+=$value; //adds $value to $sum
//echo "$value <br>";
}
echo $sum;
?>
for the count count($myArray); makes the most senses but you could do that in the loop as well:
<?php
$myArray = array(87,75,93,95);
$sum= $count=0;// initiate interger variables
foreach($myArray as $value){
$sum+=$value; //adds $value to $sum
$count++; //add 1 on every loop
}
echo $sum;
echo $count;
//the basic math for any average:
echo $sum/$count;
?>
if you don't create $sum and $count before the loop you would get notices returned from php, as the first time it tried to add to either, there would be noting to add to
You could:
$avg = array_sum($myArray) / count($myArray);
echo $avg;
Where:
array_sum calculates the sum of all elements in the given array.
count outputs the total number of elements in the given array.

putting a foreach inside foreach

I'm trying to loop some array using foreach.
This is the code which demonstrates what I'm doing:
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-".$key2."-".$val2;
}
}
However, this outputs
32-0-5
32-1-3
32-2-2
32-3-1
and I want to display it like this instead
32-1-5
45-2-3
67-3-2
89-3-1
How can I solve this? Since I'm a beginner I don't know what to do.
You don't want to loop over the 2nd array, you just want to get the value at a certain position. Try it like this:
foreach($arr1 as $key => $val){
$val2 = $arr2[$key];
echo $val."-".($key+1)."-".$val2;
}
I assume you're doing a double foreach because you actually want to print 4*4 = 16 rows. I also assume that you mistyped the last row, where you have a 3 instead of a 4.
Just using ($key2+1) can be enough for you ?
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-" . ($key2+1) . "-".$val2;
}
}
Do not nest the loops;
Use one loop and print array1[i]."-".array2[i]
You can use for loop instead of foreach too:
$arr1=array(32,45,67,89);
$arr2=array(5,3,2,1);
for ($i = 0; $i < 4; $i++) {
echo $arr1[$i] . "-" . ($i+1) . "-" . $arr2[$i];
}
$i<count ($arr1) counts the number of elements in the array.
And then stop once it gets to the end.
If you have the name number of elements in each array. This would be great for you or even to create tables dynamically.
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
for ($i=0; $i<count ($arr1) ; $i++){
echo $arr1[$i] . "-" . $arr1[$i]."-". $arr2[$i] ;
}

Foreach loop, but for first key do something else

Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");

How do I get max(); to display the highest value number rather than just "Array"?

max($caption);
gives me this:
Array
$caption is defined here:
$i = "0";
while ($i < $count) {
list($oldCaption, $year, $order) = explode("-", $galleryDirectory[$i]);
$caption[$year][$order] = str_replace("_", " ", "$oldCaption");
echo $year; //debug
echo "<br />";
$i++;
}
$year comes out to be
2008
2009
2009
so how do I get max($caption); to give me the value of 2009 rather than Array?
also i would put the whole code, but when i tried that it turned out messy. but I will try again, so you guys can see the whole pictures
Use array_keys():
$years = array_keys($caption);
$maxYear = max($years);
// or the one-liner:
$maxYear = max(array_keys($caption));
The reason why your code wasn't working is that you were comparing the values of the array $caption, which is an another array. max() compares int values, not keys nor arrays. By using array_keys() on $caption creates another array with all years as values.

Categories