Basic implode foreach - php

I have the following code of which I want to echo array elements separated by commas. The code outputs the disered list, but without commas. What am I missing?
<?php
$array = get_field('casts');
$elements = $array;
foreach($array as $key => $value) {
echo implode(', ', $value)};
?>
EDIT 1: where $elements are nested arrays.
EDIT 2: Working snippet:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>

Why are you assigning $elements = $array; and then never using $elements?
Also you don't need to loop (foreach) to implode an array.
Try this:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
// this array_push() function adds $value to the end of $new_array.
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Here is the documentation on implode()
You can play around and test the above code here.
Also next time, add the tag php, otherwise our codes won't get color syntax.

Related

concatinating two array elements with a string within a foreach loop

I am trying to combine two array elements with the string "OR" and create one string of elements.
The array looks like this:
$myarray = array(2282396,1801345)
This is the code i have used.
$bool = ' OR ';
foreach($myarray as $element){
echo $element .= $bool;
}
I trying to get this output after looping using a foreach loop.
2282396 OR 1801345
However, the output i get looks like this:
2282396 OR 1801345 OR
How do i get rid of the 'OR' after the second element? Thanks in advance
You have to check if you're in the first/last iteration or not.
$first = true;
$bool = ' OR ';
foreach ($myarray as $element) {
if (!$first) {
echo $bool;
}
echo $element;
$first = false;
}
If your array is indexed by numeric indexes 0-x, you an use
$bool = ' OR ';
foreach ($myarray as $key => $element) {
if ($key > 0) {
echo $bool;
}
echo $element;
}
Use implode as:
echo implode(" OR ", $myarray);
Documentation implode
Live example: 3v4l

exploade accosiative array type data

I have data like following
string(133) "lindsey#testmail.com=>5.jpg,rickey#testmail.com=>6.jpg,darnell#testmail.com=>84.jpg,ball#gmail.com =>49.jpg,norton#tesing.com=>68.jpg"
i want to explode email and image separately.
i use explode but it didn't work.
i also try associative array.
here is my code but it didn't work.
foreach ($array as $key => $value ) {
echo $key;
echo "<li><img src=\"".base_url()."images/menters/".$values."\" class=\"img-border\"/><span>icon</span></li>\n";
}
i think it happen additional string(133)
i have no idea how to accomplish this
You can't do that with a single explode, you have to explode the string twice. You can then use an associative array to store values and use them
$array = explode(',' $string);
foreach ($array as $key => $val) {
$exp = explode('=>', $val);
$assoc_array[$key]['mail'] = $exp[0];
$assoc_array[$key]['img'] = $exp[1];
}
foreach ($assoc_array as $val) {
echo 'Mail : ', $val['mail'], '<br>';
echo 'Image : ', $val['img'];
}

Making a dynamic array

THE ANSWER THAT WORKED FOR ME BASED ON AN ANSWER GIVEN
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
$array = array_merge($array, $push);
}
So I'm trying to display tags from my data base and make links out of them like this:
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
$array = array();
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_push($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
<? }
?>
However all I get back is
Array
Where I should be having at least three lines as was previously produced by
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
while($post = mysql_fetch_array($tags)) {
$array = explode(',', $post['tags']);
foreach ($array as $value) {?>
<? echo $value?>
<? }
}
?>
The code being called looks like this:
tag1, tag2, tag3
Tried
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_merge($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
now foreach doesn't return a value
Use array_merge(), because array_push() will push the output of explode(), which is an array, as a whole to the array in the first argument, creating a jagged array.
As for your edit, this works:
$array = array_merge($array, $push);
foreach ($array as $value)
{
echo '' . $value . '';
}
Please note that array_merge() (contrary to array_push(), gotta love the consistency) does not alter the array passed as its first argument, so you'll have to store the return value which I do on the first line ($array = ...).
While outputting to HTML, you also might want to put a $value = htmlentities(trim($value)); in the foreach loop.

Copy values into another array

I have the following code:
foreach ($row as $item) {
foreach($item as $key) {
echo "<pre>";
print_r($key);
echo "</pre>";
}
}
I am trying to copy the keys ($key) into another array for further processing. How can i do this?
define some variable as array $array = array(); and just push the keys in with array_push($array, $key);
$array = array();
foreach ($row as $item) {
foreach($item as $key) {
array_push($array, $key);
}
}
$aNew = array();
foreach($row as $item) {
foreach($item as $key) {
$aNew[] = $key;
}
}
But; why would you do this? You can also just perform your commands / processing inside the second foreach().
If you want to get all keys of an array you may use
array_keys()
instead. Also, if each of your rows has the same keys in your second foreach loop, you may break both of the loops after getting all the keys from the first row.
Just use array_keys()
$a = array();
$array_of_keys = array_keys( $a );

return monodimensional-array from multidimensional

I have a multidimensional array:
$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
1=>array('text'=>'text2','desc'=>'blablabla'),
2=>array('text'=>'blablabla','desc'=>'blablabla'));
Is there a function to return a monodimensional array based on the $text values?
Example:
monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');
Maybe a built-in function?
This will return array with first values in inner arrays:
$ar = array_map('array_shift', $array);
For last values this will do:
$ar = array_map('array_pop', $array);
If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):
$ar = array_map(function($a) {
return $a[(key you want to return)];
}, $array);
Do it like this:
function GetItOut($multiarray, $FindKey)
{
$result = array();
foreach($multiarray as $MultiKey => $array)
$result[$MultiKey] = $array[$FindKey];
return $result;
}
$Result = GetItOut($multiarray, 'text');
print_r($Result);
Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.
The foreach loop would look something like:
function monoarray($myArray) {
$output = array();
foreach($myArray as $key=>$value) {
if( $key == 'text' ) {
$output[] = $value;
}
}
return $output;
}
If the order of your keys never changes (i.e.: text is always the first one), you can use:
$new_array = array_map('current', $array);
Otherwise, you can use:
$new_array = array_map(function($val) {
return $val['text'];
}, $array);
Or:
$new_array = array();
foreach ($array as $val) {
$new_array[] = $val['text'];
}
Try this:
function monoarray($array)
{
$result = array();
if (is_array($array) === true)
{
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
{
$result[] = $value;
}
}
return $result;
}
With PHP, you only have to use the function print_r();
So --> print_r($array);
Hope that will help you :D

Categories