PHP Echo out values of an array with ranges - php

I am still learning PHP and have a bit of an odd item that I haven't been able to find an answer to as of yet. I have a multidimensional array of ranges and I need to echo out the values for only the first & third set of ranges but not the second. I'm having a hard time just finding a way to echo out the range values themselves. Here is my code so far:
$array = array(
1=>range(1,4),
2=>range(1,4),
3=>range(1,4)
);
foreach(range(1,4) as $x)
{
echo $x;
}
Now I know that my foreach loop doesn't even reference my $array so that is issue #1 but I can't seem to find a way to reference the $array in the loop and have it iterate through the values. Then I need to figure out how to just do sets 1 & 3 from the $array. Any help would be appreciated!
Thanks.

Since you don't want to show the range on 2nd index, You could try
<?php
$array = array(
1=>range(1,4),
2=>range(1,4),
3=>range(1,4)
);
foreach($array as $i=>$range)
{
if($i!=2)
{
foreach($range as $value)
{
echo $value;
}
}
}
?>
Note: It's not really cool to name variables same as language objects. $array is not really an advisable name, but since you had it named that way, I didn't change it to avoid confusion

Do you want to do this?
foreach ($array as $item) {
echo $item;
}

You can use either print_r($array) or var_dump($array).
The second one is better because it structures the output, but if the array is big - it will not show all of it content. In this case use the first one - it will "echo" the whole array but in one row and the result is not easy readable.

Range is just an array of indexes, so it's up to you how to your want to represent it, you might want to print the first and the last index:
function print_range($range)
{
echo $range[0] . " .. " . $range[count($range) - 1] . "\n";
}
To pick the first and the third range, reference them explicitly:
print_range($array[1]);
print_range($array[3]);

here is one solution:
$array = array(
1=>range(1,4),
2=>range(1,4),
3=>range(1,4)
);
$i=0;
foreach($array as $y)
{ $i++;
echo "<br/>";
if($i!=0){ foreach($y as $x)
{
echo $x;
}
}
}

Related

How can I output 2 random values from an array?

I'm trying to make a simple PHP script for school. I need to output 2 random students from the array $leerlingen (Leerlingen = students).
It work's fine when I use echo $leerlingen within the foreach loop, but when I use the return statement it stops executing, because when return is used, it ends the function.
Code:
$leerlingen = array("tobias", "hasna", "aukje", "fred", "sep", "koen", "wahed", "anna", "jackie", "rashida", "winston", "sammy", "manon", "ben", "karim", "bart", "lisa", "lieke");
shuffle($leerlingen);
function maakGroepjes($leerlingen) {
$begin = 1;
foreach ($leerlingen as $leerling) {
if ($begin <= 2) {
echo $leerling;
$begin++;
}
}
}
echo maakGroepjes($leerlingen);
Can anyone tell me how to solve this problem?
You can return only one value inside a function, in this case is an array. I assume that the array have at least two values.
<?php
$leerlingen = array(
"tobias", "hasna", "aukje", "fred", "sep", "koen", "wahed", "anna", "jackie", "rashida", "winston", "sammy", "manon", "ben", "karim", "bart", "lisa", "lieke"
);
shuffle($leerlingen);
function maakGroepjes($leerlingen) {
//your result array
$result = array();
//Picking 2 random entries out of an array to $keys
$keys = array_rand($leerlingen, 2);
//Returning the array with two values
return array($leerlingen[$keys[0]], $leerlingen[$keys[1]]);
}
//assign the values to the vars
list($one, $two) = maakGroepjes($leerlingen);
//printing
echo $one . "<br>\n";
echo $two . "<br>\n";
?>
array_rand and other functions (rand) that rely on libc have a bad standard distribution. I'd always recommend using mt_rand() if you need it to be equally distributed, otherwise some entries will be heavily favored.
This is a good easy replacement for numerical arrays:
function array_mt_rand($array) {
return $array[ mt_rand( 0, count($array)-1 ) ];
}
$one = array_mt_rand($array);
$two = array_mt_rand($array);
You may need some extra checks if you have a small array and always want two distinct values though.
You could always try something like this.
function maakGroepjes($leerlingen) {
do {
$first_student = array_rand($leerlingen);
$second_student = array_rand($leerlingen);
} while ($leerlingen[$first_student] == $leerlingen[$second_student]);
return [$leerlingen[$first_studen], $leerlingen[$second_student]];
}
Which returns this.
Array
(
[0] => manon
[1] => winston
)
Also, the difference between a function printing/echo'ing information and returning information is pretty big.
You can't assign a variable to the echo statement inside of a function, whereas you could assign a variable to the return statement.
I would approach this a little differently.
function maakGroepjes($leerlingen) {
shuffle($leerlingen); // randomize the list of students
return array_chunk($leerlingen, 2); // break in into groups of two and return it
}
Then with
$groepjes = maakGroepjes($leerlingen);
you can generate all of the groups at once. No worries about repetition. This way if you need multiple groups, you can loop over the list of groups. If you really only need one group of two, then that will be
$groepjes[0];
which you can ouptut however you like. A very simple example:
foreach ($groepjes[0] as $student) echo "$student<br>";
Try this:
if ($begin <= 2) {
echo $leerling;
$begin++;
} else {
return
}
What this does is: every time through the loop, it looks at $begin. If it's less than or equal to two, it echoes that student and increments $begin. Otherwise, if it's greater than two, it returns, ending the function (and thus, the loop).
A perhaps better way to do it would be to just look at the ordinal directly:
foreach ($leerlingen as $ord => $leerling) {
echo $leerling;
if ($ord == 1) return;
}
Note the syntax in the loop definition. The "old =>" part sets the ordinal value as a variable as you loop through, letting you see which entry in the array you are currently on. So, this just loops through printing students. When it has printed the second student (remember, arrays are counted 0, 1, 2...) it returns.
Also, you probably don't want to echo maakGroepjes(). That function is what is echoing the student names. You probably don't want to echo the function result unless the function compiles the names into a string and returns the string or something.

Start foreach loop on associative array at the second element

I have associative array such as:
$myArray = array(
'key1' => 'val 1',
'key2' => 'val 2'
...
);
I do not know the key values up front but want to start looping from the second element. In the example above, that would be from key2 onwards.
I tried
foreach(next(myArray) as $el) {
}
but that didnt work.
Alternatives may be array_slice but that seems messy. Am i missing something obvious?
There really is no "one true way" of doing this. So I'll take it as a benchmark as to where you should go.
All information is based on this array.
$array = array(
1 => 'First',
2 => 'Second',
3 => 'Third',
4 => 'Fourth',
5 => 'Fifth'
);
The array_slice() option. You said you thought this option was overkill, but it seems to me to be the shortest on code.
foreach (array_slice($array, 1) as $key => $val)
{
echo $key . ' ' . $val . PHP_EOL;
}
Doing this 1000 times takes 0.015888 seconds.
There is the array functions that handle the pointer, such as ...
current() - Return the current element in an array.
end() - Set the internal pointer of an array to its last element.
prev() - Rewind the internal array pointer.
reset() - Set the internal pointer of an array to its first element.
each() - Return the current key and value pair from an array and advance the array cursor.
Please note that the each() function has been deprecated as of PHP 7.2, and will be removed in PHP 8.
These functions give you the fastest solution possible, over 1000 iterations.
reset($array);
while (next($array) !== FALSE)
{
echo key($array) . ' ' . current($array) . PHP_EOL;
}
Doing this 1000 times, takes 0.014807 seconds.
Set a variable option.
$first = FALSE;
foreach ($array as $key => $val)
{
if ($first != TRUE)
{
$first = TRUE;
continue;
}
echo $key . ' ' . $val . PHP_EOL;
}
Doing this 1000 times takes 0.01635 seconds.
I rejected the array_shift options because it edits your array and you've never said that was acceptable.
This depends on whether you want to do this just once or many times, and on whether you still need the original array later on.
"First" pattern
$first = true;
foreach ($array as $key=>value) {
if($first) {
$first = false;
continue;
}
// ... more code ...
}
I personally use this solution quite often because it's really straight-forward, everybody gets this. Also, there is no performance hit of creating a new array and you can still operate on the original array after the loop.
However, if you have a couple of loops like this, it kind of starts looking a little unclean, because you need 5 extra lines of code per loop.
array_shift
array_shift($array);
foreach ($array as $key=>value) {
// .... more code ....
}
array_shift is a function tailored to this special case of not wanting the first element. Essentially it's a Perl-ish way of saying $array = array_slice($array, 1) which might not be completely obvious, especially since it modifies the original array.
So, you might want to make a copy of the original array and shift it, if you need both the shifted array multiple times and also the original array later on.
array_slice
And, of course, there is array_slice itself. I don't see anything wrong with array_slice if you want the original array to remain unchanged and you need the sliced array multiple times. However, if you're positive that you always want to slice just one element off, you might as well use the shorthand array_shift (and make a copy before if needed).
You can go with the obvious way:
$flag = false;
foreach($myArray as $el) {
if($flag) {
// do what you want
}
$flag = true;
}
Just another way of flexible iteration:
reset($myArray); // set array pointer to the first element
next($myArray); // skip first element
while (key($myArray) !== null) {
// do something with current($myArray)
next($myArray);
}
As far as I know foreach is just a kind of shortcut for this construction.
From Zend PHP 5 Certication study guide:
As you can see, using this set of functions [reset, next, key,
current, ...] requires quite a bit of work; to be fair, there are some
situations where they offer the only reasonable way of iterating
through an array, particularly if you need to skip back-and-forth
between its elements. If, however, all you need to do is iterate
through the entire array from start to finish, PHP provides a handy
shortcut in the form of the foreach() construct.
If your array was 0 based, it would be if($key>=1), but as your array starts at key 1, then this should work.
foreach ($array as $key=>$value){if($key>=2){
do stuff
}}
You could try:
$temp = array_shift($arr);
foreach($arr as $val) {
// do something
}
array_unshift($arr, $temp);
reset($myArray);
next($myArray);
while ($element = each($myArray))
{
//$element['key'] and $element['value'] can be used
}
My fairly simple solution when this issue pops up. It has the nice advantage of being easily being modified to be able to skip more than just the first element if you want it to.
$doomcounter = 0;
foreach ($doomsdayDevice as $timer){ if($doomcounter == 0){$doomcounter++; continue;}
// fun code goes here
}

How to implement loop and calculate the value in php

As a php beginner, I meet a problem with calculating the elements of array in php
$effect=array("a"=>array(1,2),"b"=>array(1,2),"c"=>array(1,2));
I just want to make the result as this
$effect['a'][0]=$effect['a'][0]/$effect['a'][1];
$effect['b'][0]=$effect['b'][0]/$effect['b'][1];
$effect['c'][0]=$effect['c'][0]/$effect['c'][1];
Except do this one by one , How to do this calculation with foreach or other loop way
Your array syntax is a bit off. It should be $effect['a'][0].
The loop is trivial, and foreach was the right idea.
You can use it to iterate over all the letters using:
foreach ($effect as $letter => $numbers) {
...
}
Then put your assignment/division line in the loop, replacing the fixed 'a' and 'b' etc. with the $letter variable.
You need something like this?
foreach ($effect as $key => $val)
{
$results[$key] = $val[0] / $val[1];
}
print_r($results);
Also one counter-intuitive thing in PHP, is that arrays are passed by value by default. You can use & to get a reference to the array
$effects =array("a"=>array(1,2),"b"=>array(1,2),"c"=>array(1,2));
foreach ( $effects as $key => &$effect ) {
$effect[0] = $effect[0]/$effect[1];
unset($effect);
}
print_r( $effects );

Using PHP's "for". Instead of sequential numbers, use specific numbers

I'm pretty new to PHP and want to write a "for" statement based on IDs of a page. The problem is that the IDs are not sequential (by that I mean they are not increasing by 1 each time ie. 1,2,3,4,5). Is there a way to use "for" to use specific numbers? For example (pseudocode)
for IDnumbers i = (1,5,7,23,28,34)
echo "function1(i)"
echo "function2(i)"
end
I hope that makes sense. I basically want functions associated with each post ID to be returned, but I want the IDnumbers to be specific. Sorry if this is a basic question!
edit: wow, that really was basic. Thanks guys!
// create an array
$numbers = array(1,5,7,23,28,34);
// loop over it
foreach($numbers as $number){
echo function1($number);
echo function2($number);
}
foreach (array(1,5,7,23,28,34) as $n) {
echo "function1($n)";
echo "function2($n)";
}
foreach( Array(1,5,7,23,28,34) as $i) {
// do stuff with $i
}
Store the numbers in an array and use a foreach.
$IDNumbers = array(1,5,7,23,28,34);
foreach($nums as $num)
{
echo function1($num);
echo function2($num);
}
Read more about php foreach here.
try something like this:
IDnumbers = array(1,5,7,23,28,34)
foreach IDnumbers as id
echo "function1(id)"
echo "function2(id)"
end
IF you MUST use FOR, then you can do this:
$IDNumbers = (1,5,7,23,28,34);
for($i = 0; $i < count($IDNumbers); $i++):
echo function1($IDNumbers[$i]);
endfor;
This is because even though you stored a number as the value in a numeric array, it still orders it sequentially in reference to the identifiers and where they were added. The value may be 7, but its pointer is 2 (0, 1, 2, 3, 4, 5 in this case)

How to start a foreach loop at a specific index in PHP

I am writing a foreach that does not start at the 0th index but instead starts at the first index of my array. Is there any way to offset the loop's starting point?
Keep it simple.
foreach ($arr as $k => $v) {
if ($k < 1) continue;
// your code here.
}
See the continue control structure in the manual.
A Foreach will reset the array:
Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Either use a for loop (only if this is not an associative array)
$letters = range('a','z');
for($offset=1; $offset < count($letters); $offset++) {
echo $letters[$offset];
}
or a while loop (can be any array)
$letters = range('a','z');
next($letters);
while($letter = each($letters)) {
echo $letter['value'];
}
or with a LimitIterator
$letters = new LimitIterator(new ArrayIterator(range('a','z')), 1);
foreach($letters as $letter) {
echo $letter;
}
which lets you specify start offset and count through the constructor.
All of the above will output the letters b to z instead of a to z
You can use the array_slice function:
$arr = array(); // your array
foreach(array_slice($arr, 1) as $foo){
// do what ever you want here
}
Of course, you can use whatever offset value you want. In this case, 1 'skip' the first element of the array.
In a foreach you cant do that. There are only two ways to get what you want:
Use a for loop and start at position 1
use a foreach and use a something like if($key>0) around your actual code
A foreach does what its name is telling you. Doing something for every element :)
EDIT: OK, a very evil solution came just to my mind. Try the following:
foreach(array_reverse(array_pop(array_reverse($array))) as $key => $value){
...
}
That would reverse the array, pop out the last element and reverse it again. Than you'll have a element excluding the first one.
But I would recommend to use one of the other solutions. The best would be the first one.
And a variation: You can use array_slice() for that:
foreach(array_slice($array, 1, null, true) as $key => $value){
...
}
But you should use all three parameters to keep the keys of the array for your foreach loop:
Seems like a for loop would be the better way to go here, but if you think you MUST use foreach you could shift the first element off the array and unshift it back on:
$a = array('foo','bar');
$temp = array_shift($a);
foreach ( $a as $k => $v ) {
//do something
}
array_unshift($a, $temp);
Well no body said it but if you don't mind altering the array and if we want to start from the second element of the given array:
unset($array[key($array)]);
foreach($array as $key=>$value)
{
//do whatever
}
if you do mind, just add,
$saved = $array;
unset($array[key($array)]);
foreach($array as $key=>$value)
{
//do whatever
}
$array = $saved;
Moreover if you want to skip a given known index, just subtitute
key($array)
by the given index
bismillah...
its simple just make own keys
$keys=1;
foreach ($namafile_doc as $value ) {
$data['doc'.$keys]=$value;
$keys++;
}
may this answer can make usefull

Categories