Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Have those syntaxes:
Foreach:
$array=array('v1','v2','v3');
foreach( $array as $value ){
echo $value;
}
Output:
v1v2v3
Implode:
$array=array('v1','v2','v3');
$value=implode(" ",$array);
echo $value;
Output:
v1 v2 v3
I need some help understanding the difference between implode(),foreach() used in the situation above.Are they the same? Or what is the difference? Which i should use and when?
For the record,i know small differences,and things like that.I just want to know your opinion and if there is something i didn't know about those functions.
Generally loops may be used for making any action you want.
You can for example concatenate string with other string depending or array element:
$array=array('v1','v2','v3');
foreach ($array as $value) {
if ($value == 'v1') {
echo $value.' something';
}
else {
echo $value.' something2';
}
}
and if you have numbers in your array you can do math operations:
$array=array(1,2,3);
foreach ($array as $value) {
echo ($value + 5).' ';
}
You can also change array elements:
$array=array(1,2,3);
foreach ($array as &$value) {
$value += 3;
}
unset($value);
foreach ($array as $value ){
echo $value.' ';
}
// result: 4 5 6
Implode is just a function that merge array elements and put a splitter between them. Nothing more. It doesn't change array elements. It simple returns output string. It's usually used for preparing data to display.
Also implode is much more convenient for putting splitter between elements. In loop if you want to put space between all elements but you don't need to put space after last element you need to make extra checks for last element and using implode you don't need to care because implode just does it for you.
And in your case, output wouldn't be the same because your loop would output:
v1v2v3 and implode would output v1 v2 v3 because you used space separator
foreach is a loop statement. implode is a function. That's the difference. You are supposed to use foreach for any kind of operation for each element in an array. But implode is a helper method that binds the elements of the given array by using the given string as binder.
foreach() : it's a looping concept means you get values one by one and print you will found each result/value seperate while you not concat that.
implode() : convert an array to string with passsing glue. and you will get all array values in one string.
implode() also iterating array internally, and converting array into string
loop is also doing same thing here,
loop advantage here
1) when you want to conditional part, for instance
you want to exclude v2 from string or other operation depend on requirement
$array=array(1,2,3);
foreach ($array as $value ){
if($value == 2) continue;
echo $value." ";
}
these things can't apply in implode function
2) In loop you can direct buffer output or append into string.. [this is denpend on requirement],
import is only function that is combine array values into string.
how can it be same, both r used in different places. for example
list($y,$m,$d)=explode("-",$query); //separating and storing in variable `y-m-d`
$arr=array($m,$d);
$cat=implode('-',$arr); //u got that format again with only two variables
implode expects array.
where foreach is a loop which iterates through given array() until and unless it meets the false condition and gets out of the loop
Related
For example i have an array like this [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3]
I want to count the element which are not -1 like except of the -1. Is there any function in php to get this ? One approach which i think is
Count the total array - count of the -1 in the array.
how can we achieve this.
P.S : please provide me a comment why this question deserve negative vote.
Like #MarkBaker said, PHP doesn't have a convenient function for every single problem, however, you could make one yourself like this:
$arr = [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3];
function countExcludingValuesOfNegativeOne ($arr) {
return count($arr) - array_count_values(array_map('strval', $arr))['-1'];
}
echo countExcludingValuesOfNegativeOne($arr); // Outputs `2`.
It just counts the whole array, then subtracts the number of negative 1s in the array. Because PHP throws an error if any element in the array isn't a string 1 when using array_count_values, I've just converted all elements of the array to a string using array_map('strval', $arr) 2
you can use a for loop counter skipping for a specific number.
function skip_counter($array,$skip){
$counter = 0;
foreach ($array as $value) {
if ($value != $skip) $counter++;
}
return $counter;
}
then you call skip_counter($your_list, $number_to_be_skipped);
This question already has answers here:
Get and remove first element of an array in PHP
(2 answers)
Closed 8 years ago.
I have a range of fourier transform values in php as shown below.
[8974,398.22605659378,340.40931712583,224.61805748557,224.21476160103,531.02102311671,348.09311299013,74.373164045484,440.15451832283,379.54095616825,801.05398080895,184.15175862698,539.59590498835,114.82864261836,595.84662567888,488.12623039438,370,488.12623039438,595.84662567888,114.82864261836,539.59590498835,184.15175862698,801.05398080895,379.54095616825,440.15451832283,74.373164045484,348.09311299013,531.02102311671,224.21476160103,224.61805748557,340.40931712582,398.22605659378]
How do I actually ignore/delete away the first value in this case "8974" in php language?
You can use array_shift();
Like
$array=array(8974,398.22605659378,340.40931712583,224.61805748557,224.21476160103,531.02102311671,348.09311299013,74.373164045484,440.15451832283,379.54095616825,801.05398080895,184.15175862698,539.59590498835,114.82864261836,595.84662567888,488.12623039438,370,488.12623039438,595.84662567888,114.82864261836,539.59590498835,184.15175862698,801.05398080895,379.54095616825,440.15451832283,74.373164045484,348.09311299013,531.02102311671,224.21476160103,224.61805748557,340.40931712582,398.22605659378);
array_shift($array);
print_r($array);
You could use array_shift
ie:
$myArray = array(8974,398.22605659378,340.40931712583,224.61805748557,224.21476160103,531.02102311671,348.09311299013,74.373164045484,440.15451832283,379.54095616825,801.05398080895,184.15175862698,539.59590498835,114.82864261836,595.84662567888,488.12623039438,370,488.12623039438,595.84662567888,114.82864261836,539.59590498835,184.15175862698,801.05398080895,379.54095616825,440.15451832283,74.373164045484,348.09311299013,531.02102311671,224.21476160103,224.61805748557,340.40931712582,398.22605659378);
array_shift($myArray)
You can easily unset first element to Delete it:
unset($array[0]);
Ignore it
Create a temporary array from the first by skipping the first element:
foreach (array_slice($arr, 1) as $xyz) {
/// ...
}
Or, without creating a temporary array:
reset($arr); next($arr); // reset and skip first element
while (list($key, $value) = each($arr)) {
echo $value;
}
Modify it
Modify the array in place by shifting the first item off:
array_shift($arr);
// do whatever you want
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;
}
}
}
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 );
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Is it possible to explode an array like this.
$arr=array();
$arr[0]['id']='123';
$arr[0]['otherdatas']=
$arr[1]['id']='234';
$arr[1]['otherdatas']=
$arr[2]['id']='567';
echo "string: ".explode($arr[]['id'],',');
and end up with this?
string: 123,234,567
Doing the above results in:
Fatal error: Cannot use [] for reading in /data/www/test.php on line 8
How can I go about this without doing something like...
function getIDs(){
foreach($arr as $val){
if($string){$string.=',';}
$string.=$arr['id'];
}
return $string;
}
Is there some better way to go about this?
First of all, you're trying to implode the strings, not explode. Secondly, no, there's no syntax shortcut for expressing the operation "join all id keys in all sub arrays together". You can do it very concisely like this though:
echo join(',', array_map(function ($i) { return $i['id']; }, $arr));
From PHP5.5 and up, you can call array_column() to isolate a single column of data in your multi-dimensional array.
Code: (Demo)
$arr=array();
$arr[0]['id']='123';
$arr[0]['otherdatas']='';
$arr[1]['id']='234';
$arr[1]['otherdatas']='';
$arr[2]['id']='567';
echo implode(',',array_column($arr,'id'));
Output:
123,234,567
no, it`s impossible.
function myExplode ($data=array(),$row='id',$delimiter=','){
$result='';
foreach ($data as $item) $result.=($data[$row])?$delimiter.$data[$row]:'';
return $result;
}