Array To String Conversion error from a double array - php

I am trying to do a double array to echo out "brown dog" and "white cat". I got an "Array to string conversion" error on the line where I am trying to echo out the statement. How can I fix this error? Thanks in advance. Below is my code:
<?
$pet1 = "dog";
$pet2 = "cat";
$arrayvalue = array();
$arrayvalue[0] = array("brown, "white");
$arrayvalue[1] = array("$pet1", "$pet2");
foreach($arrayvalue as $array)
{
echo "$arrayvalue[0] &nbsp $arrayvalue[1] </br>";
}
?>

The only way I can see this working is with a for loop. If you need to keep the current structure as it is, do this:
for ($i=0; $i<2; $i++)
echo $arrayvalue[0][$i] . ' ' . $arrayvalue[1][$i] . '<br>';
Here is how I would rewrite the program, keeping the current array structure and using the above for loop to solve your problem:
$pet1 = 'dog';
$pet2 = 'cat';
$arrayvalue = array(
array('brown', 'white'),
array($pet1, $pet2)
);
for ($i=0; $i<2; $i++)
echo $arrayvalue[0][$i] . ' ' . $arrayvalue[1][$i] . '<br>';
Output:
brown dog
white cat

You need to edit the foreach loop a little. Also, there's a problem with your quotes above. Try:
<?
$pet1 = "dog";
$pet2 = "cat";
$arrayvalue = array();
$arrayvalue[0] = array("brown", "white");
$arrayvalue[1] = array("$pet1", "$pet2");
foreach( $arrayvalue[0] as $key => $color ) {
echo "$color &nbsp $arrayvalue[1][$key] </br>";
}
?>
Basically instead of iterating through $arrayvalue, you should be going through the one with the colors or the one with the pets. In my example, I go through the one with the colors, and then reference the one with the pets, using $key to keep them in sync.
If possible, I would recommend using two separate arrays instead of one, or naming it more logically:
$array['colors'] = array("brown", "white");
$array['pets'] = array("$pet1", "$pet2");
foreach( $array['colors'] as $key => $color ) {
echo "$color &nbsp $array['pets'][$key] </br>";
}
//or
$colors = array("brown", "white");
$pets = array("$pet1", "$pet2");
foreach( $colors as $key => $color ) {
echo "$color &nbsp $pets[$key] </br>";
}

You are referencing $arrayvalue inside your foreach loop, when you should be using $array
foreach($arrayvalue as $array)
{
echo "{$array[0]} &nbsp {$array[1]} </br>";
}

Related

Add new data in foreach loop multidimensional array

I try to add new data in a multidimensional array for each loop, but it wont work.
This shows the values in my array:
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
$klanten['newData'] = 'test';
}
}
With $klanten['newData'] = 'test'; I try to add "test" to each array, but it won't work.
I also tried to use this, AFTER the script above:
foreach ($klanten as &$item ){
$item['newData'] = 'test';
}
That will work, but I think there must be an option to do it in the foreach loop above the first time. How can I do that?
Hi so you got most of it right but, you see when you are looping around a variable and adding a new item in it you have to make sure to give a index for that new array index so...
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
// $klanten['newData'] = 'test'; // instead of this
$klanten[$key]['newData'] = 'test'; // do this
}
}
This will save each and every value of newData index according to its key in $klanten array.

Loop through 3 elements in array

i can loop through 2 elements in an array , but here im having trouble looping through 3 elements .
this is my example :
$y = array('cod=>102,subcod=>10201,name=>"blabla"',
'cod=>103,subcod=>10202,name=>"blibli"',
'cod=>103,subcod=>10202,name=>"bblubl"')
my desire result is how to get the value of cod and subcod and name of every line .
I tried this :
foreach ($y as $v) {
echo $v['cod'] ;
echo $v['subcod'];
echo $v['name'] ;
}
but didnt work , im getting this error : Warning: Illegal string offset 'cod' and same error for every offset .
any help would be much apreciated.
If you can't change you're array
Then you need to format that and then use the loop and get the value.
function format_my_array($arg) {
$new = array();
foreach( $arg as $n => $v ) {
// splitting string like
// 'cod=>102,subcod=>10201,name=>"blabla"'
// by comma
$parts = explode(',', $v);
$new[$n] = array();
foreach( $parts as $p ) {
// splittin again by '=>' to get key/value pair
$p = explode('=>', trim($p));
$new[$n][$p[0]] = $p[1];
}
}
return $new;
}
$new_y = format_my_array($y);
foreach( $new_y as $v ) {
echo $v['cod'];
echo $v['subcod'];
echo $v['name'];
}

php foreach echo prints "Array" as value

Perhaps I'm simply having trouble understanding how php handles arrays.
I'm trying to print out an array using a foreach loop. All I can seem to get out of it is the word "Array".
<?php
$someArray[]=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?>
<br />
<?php
}
?>
This prints out this:
Array
I'm having trouble understanding why this would be the case. If I define an array up front like above, it'll print "Array". It almost seems like I have to manually define everything... which means I must be doing something wrong.
This works:
<?php
$someArray[0] = '1';
$someArray[1] = '2';
$someArray[2] = '3';
$someArray[3] = '4';
$someArray[4] = '5';
$someArray[5] = '6';
$someArray[6] = '7';
for($i=0; $i<7; $i++){
echo $someArray[$i]."<br />";
}
?>
Why won't the foreach work?
here's a link to see it in action >> http://phpclass.hylianux.com/test.php
You haven't declared the array properly.
You have to remove the square brackets: [].
<?php
$someArray=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?> <br />
<?php
}
?>
Try:
<?php
$someArray = array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value . "<br />\n";
}
?>
Or:
<?php
$someArray = array(
0 => '1',
'a' => '2',
2 => '3'
);
foreach($someArray as $key => $val){
echo "Key: $key, Value: $val<br/>\n";
}
?>
actually, you're adding an array into another array.
$someArray[]=array('1','2','3','4','5','6','7');
the right way would be
$someArray=array('1','2','3','4','5','6','7');

how to get individual element from array in php?

I have dateValues as follows,
[dateVals] = 031012,041012;
it is comma seperated values. I want to make this as array and to get individual values . As i am new to PHP , i want some one's help .
$val = array[dataVals];
for($i=0;$i<sizeof($val);$i++) {
echo "val is".$val[$i]."\n";
}
is not working
use this code
$dateVals = '031012,041012';
$pieces = explode(",", $dateVals);
for($i=0;$i<sizeof($pieces);$i++) {
echo "val is".$pieces[$i]."\n";
}
it will give you proper output.
working example http://codepad.viper-7.com/PQBiZ3
$dateVals = '031012,041012';
$dateValsArr = explode(',', $dateVals);
foreach( $dateValsArr as $date) {
}
Try this code.
Try this One
$dateVals = '031012,041012';
$date_arr[] = explode(',',$dateVals);
for($i = 0 ; $i < count($date_arr) ; $i++)
{
print $date_arr[$i].'<br />';
}

How can I easily remove the last comma from an array?

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.

Categories