I have an array which is defined as $array[colname]. For each value in $array[colname], I would like to append a piece of text to the end. The value already inside is string and I will append a string as well.
There are at least two possibilities
Edit the array in place:
foreach($a as &$v) {
$v .= 'APPENDED';
}
or
foreach($a as $k => $v) {
$a[$k] = $v . 'APPENDED';
}
Create a new array by mapping the old values to their new values:
$appended_array = array_map(function($v) { return $v . 'APPENDED'; }, $a);
Like this? You can easily iterate throug arrays
Here are the docs: http://php.net/manual/en/control-structures.foreach.php
Tip: Next time you should search on google and php.net because most default stuff are documented and in your question you used the right keywords that you needed to find it yourself
<?php
//Could write this shorter
$array = array();
$array['column1'] = 'value1';
$array['column2'] = 'value2';
//This is the short way
//http://php.net/manual/en/language.types.array.php
$array = array('column1' => 'value1', 'column2' => 'value2');
//Iterate throug every value in $array (That is every $array[colname])
//The & charachter before the $value means pass-by-reference you should do some research to understand this ;)
//foreach($array['colname'] as &$value) { for a single column with multiple values in it
foreach($array as &$value) {
// .= is the same as $value = $value . 'append'
// This way we append the text
$value .= 'append';
}
//Outputs all values in $array
print_r($array());
?>
You can use array_walk like below:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $string)
{
$item1 = "$item1 : $string";
}
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
array_walk($fruits, 'test_print');
?>
Output will be like this:
... and after:
d. lemon:fruit
a. orange:fruit
b. banana:fruit
c. apple:fruit
for more info:http://php.net/manual/en/function.array-walk.php
Here's the tested solution provided array matches to your stucture
<?php
$array = array();
$array['c1'] = array(1=>'data1', 2=>'data2', 3=>'data3', 4=>'data4');
$array['c2'] = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
echo '<pre> Original Array : <br/>';
print_r($array);
foreach($array as $key=>$value)
{
foreach($value as $sub_key=>$sub_value)
{
$textToAppend = '_AppendedMe';
echo '<br/> brfore : '.$value[$sub_key];
$sub_value .= $textToAppend;
$array[$key][$sub_key]=$sub_value;
echo '<br/> after : '.$value[$sub_key];
}
}
echo '<br/> Array after : ';
print_r($array);
echo '</pre>';
?>
Related
this code works as expected
$fruits = array("d" => "Zitrone", "b" => "Banane", "c" => "Apfel");
$fruits["a"] = "Orange";
//print_r($fruits);
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
ok, now I would like to do the same programmatically:
$collection = array();
foreach ($xml->abschnitte[0]->abschnitt as $sec) {
//echo $sec['strecke']; // this works, the strings are printed out
$collection[$sec['strecke']] = $sec['id'];
}
//print_r($collection); // nothing to see here
//ksort($collection);
foreach ($collection as $key => $val) {
echo $key . " = " . $val . "\n";
}
it seems that there no collection will be build. but there must be a way to build the key up from variables. what do i miss? thanks in advance, mischl
I have an array that looks like this:
$array = array(
array(
"http://google.com",
"Google"
),
array(
"http://yahoo.com",
"Yahoo"
)
);
What is the simplest way to loop through it. Something like:
foreach ($array as $arr) {
// help
}
EDIT: How do I target keys, for example, I want to do:
foreach ($array as $arr) {
echo '<a href" $key1 ">';
echo ' $key2 </a>';
}
In order to echo out the bits you have to select their index in each array -
foreach($array as $arr){
echo ''.$arr[1].'';
}
Here is an example.
Use nested foreach() because it is 2D array. Example here
foreach($array as $key=>$val){
// Here $val is also array like ["Hello World 1 A","Hello World 1 B"], and so on
// And $key is index of $array array (ie,. 0, 1, ....)
foreach($val as $k=>$v){
// $v is string. "Hello World 1 A", "Hello World 1 B", ......
// And $k is $val array index (0, 1, ....)
echo $v . '<br />';
}
}
In first foreach() $val is also an array. So a nested foreach() is used. In second foreach() $v is string.
Updated according to your demand
foreach($array as $val){
echo ''.$val[1].'';
}
The easiest way to loop through it is:
foreach ($array as $arr) {
foreach ($arr as $index=>$value) {
echo $value;
}
}
EDIT:
If you know that your array will have always only two indexes then you can try this:
foreach ($array as $arr) {
echo "<a href='$arr[0]'>$arr[1]</a>";
}
First modify your variable like this:
$array = array(
array("url"=>"http://google.com",
"name"=>"Google"
),
array("url"=>"http://yahoo.com",
"name"=>"Yahoo"
));
then you can loop like this:
foreach ($array as $value)
{
echo '<a href='.$value["url"].'>'.$value["name"].'</a>'
}
The way to loop through is,
foreach($array as $arr)
foreach($arr as $string) {
//perform any action using $string
}
Use the first foreach loop without { } for the simplest use.
That can be the most simple method to use a nested array as per your request.
For your edited question.
Wrong declaration of array for using key.
$array = array(
"http://google.com" => "Google",
"http://yahoo.com" => "Yahoo" );
And then, use the following.
foreach ($array as $key => $value)
echo "<a href='{$key}'>{$value}</a>";
This doesn't slow down your server's performance.
In modern versions of php, you can assign (destructure) subarray values to variables of your choosing.
A good tutorial: https://stitcher.io/blog/array-destructuring-with-list-in-php
Code: (Demo)
$array = [
["http://example1.com", "Example 1"],
["http://example2.com", "Example 2"]
];
foreach ($array as [$key1, $key2]) {
echo "$key2\n";
}
Output:
Example 1
Example 2
To be honest, I'd probably name the variables $url and $text respectively.
How can i create a new array from elements in associative array in the way that if values is integer then put that value on first place in a new array,on the second place put double,on the third place string, and on the last place number of elements. I try something like this but it doesn't work.
<?php
$array = array ('first' => 2.54, 'second' => "foo", 'third' => 1);
function myFunction($array)
{ $NewArray = array ();
$[3] = 0;
foreach($array as $value)
{
if(is_integer($value))
{echo $NewArray[0] = $value.' ';}
if(is_double($value))
{echo $NewArray[1] = $value.' ';}
if(is_string($value))
{echo $NewArray[2] = $value.' ';}
echo $NewArray[3] += 1 . ' ';}
return $NewArray;}
MyFunction ($array);
?>
Mathieu Imbert is right and you didn't describe what was wrong when you ran the code. I corrected it based on what myFunction should return (as specified in your question).
You shouldn't concatenate those values with string ' ' unless you want it with the space after the value. Finally if you want number of elements on 3rd position in returned array, don't concatenate the counter with ' ' - with that concatenation the counter would be '1 1 1 ' (for sample array from your question). Without it - 3.
Here's the corrected, tested code (I took the liberty of reformatting your code to make it easier to read and added print_r() for prettier output):
<?php
$array = array('first' => 2.54, 'second' => "foo", 'third' => 1);
function myFunction($array) {
$newArray = array();
$newArray[3] = 0;
foreach($array as $value) {
if (is_integer($value)) {
$newArray[0] = $value;
}
if (is_double($value)) {
$newArray[1] = $value;
}
if (is_string($value)) {
$newArray[2] = $value;
}
$newArray[3] += 1;
}
return $newArray;
}
print_r(myFunction($array));
?>
which outputs:
Array
(
[3] => 3
[1] => 2.54
[2] => foo
[0] => 1
)
I have a multidimensional array and I want to create new variables based on the keys.
I have written this code, but it returns NULL:
$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
if(is_array($value)){
$i = 0;
foreach($value as $v){
$i++;
$$key[$i] = $v;
}
}
}
var_dump($test);
?>
Where is the problem?
Make that:
${$key}[$i] = $v;
$$key[$i] means "the variable whose name is $key[$i]".
${$key}[$i] means "position $i from the variable whose name is $key".
Also, it would be nice if you could initialize that $test array, so you won't get notices. Add the following before the second foreach:
$$key = array();
+1 to #Radu's answer, but you should also think about if these solutions would work for you:
$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
if(is_array($value)){
$$key = array_values($value);
}
}
var_dump($test);
Or:
$a = array("test" => array("a", "b", "c"));
extract($a);
var_dump($test);
See: array_values(), extract().
$$key[$i] tries to get the variable whose name matches the value of $key[$i]. You could get a reference to $$key first, and then add an item to that reference:
$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
if(is_array($value)){
$i = 0;
foreach($value as $v){
$i++;
$x = & $$key;
$x[$i] = $v;
}
}
}
var_dump($test);
?>
[edit]
But I see, I'm somewhat slow in testing and writing an answer, since another good answer has been posted minutes ago. Still keeping this, since it uses a different and not much more complex approach.
Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.