How to echo all values from a specific array? - php

This is what I'm doing:
for($i = 0; $i <= $max; $i++) {
if(isset($media[$i])) {
$combined[] = ["type" => "media", "value" => $media[$i]];
}
if(isset($content[$i])) {
$combined[] = ["type" => "content", "value" => $content[$i]];
}
if(isset($yt[$i])) {
$combined[] = ["type" => "youtube", "value" => $yt[$i]];
}
}
echo implode(', ', array_column($combined, 'media'));
Basically I need to echo all values of "media" as a single string with value separated commas.
Tried this too:
echo implode(', ', array_map(function ($entry) {
return $entry['media'];
}, $combined));

$string = '';
foreach ( $combined as $com ) {
if ( $com['type'] === 'media' ) {
$string .= $com['value'] . ',';
}
}
$string = rtrim( $string, ','); // remove trailing comma
echo $string;

Related

how to access array position from string

I have a string containing an array key position which I am trying to use this position to access the array ($arr).
Example of string ($str) which has a string value of svg.1.linearGradient.0.#style
This would be the equivalent of ['svg'][1]['linearGradient'][0]['#style']
How can I use the string to access/retrieve data from $arr using the above position?
For example, lets say i wanted to unset the array key unset($arr['svg'][1]['linearGradient'][0]['#style']) - how can i achieve this programmatically?
You can use the mechanism of passing the value by reference:
$result = &$arr;
$path = explode('.', $str);
for($i = 0; $i < count($path); $i++) {
$key = $path[$i];
if (is_array($result) && array_key_exists($key, $result)) {
if ($i == count($path) - 1) {
unset($result[$key]); // deleting an element with the last key
} else {
$result = &$result[$key];
}
} else {
break; // not found
}
}
unset($result); // resetting value by reference
print_r($arr);
fiddle
One method could be to split the string on ., then iterate through the "keys" to traverse your $arr object. (Please excuse my poor php, it's been a while...)
Example:
$arr = (object)[
"svg" => (array)[
(object)[],
(object)[
"linearGradient" => [
(object)[
"#style" => "testing",
],
],
],
],
];
$str = "svg.1.linearGradient.0.#style";
$keys = explode('.', $str);
$val = $arr;
foreach($keys as $key) {
$val = is_object($val)
? $val->$key
: $val[$key];
}
echo $val;
https://3v4l.org/h8YPv
Unsetting a key given the path:
$arr = (object)[
"svg" => (array)[
(object)[],
(object)[
"linearGradient" => [
(object)[
"#style" => "testing",
],
],
],
],
];
$str = "svg.1.linearGradient.0.#style";
$keys = explode('.', $str);
$exp = "\$arr";
$val = $arr;
foreach($keys as $index => $key) {
$exp .= is_object($val)
? "->{'" . $key . "'}"
: "[" . $key . "]";
$val = is_object($val) ? $val->$key : $val[$key];
}
eval("unset($exp);");
https://3v4l.org/Fdo6B
Docs
explode()
eval()

PHP: Use Variable as Multiple Keys in Multi-Dimensional-Array

In a normal array you can select this way
$key='example';
echo $array[$key];
How about in a multidimensional?
$keys='example[secondDimension][thirdDimension]';
echo $array[$keys];
What's the proper way to go about this?
i think this solution is good.
note that you have to wrap all keys with "[" and "]".
$array = array(
'example' => array(
'secondDimension' => array(
'thirdDimension' => 'Hello from 3rd dimension',
)
),
);
function array_get_value_from_plain_keys($array, $keys)
{
$result;
$keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)
eval('$result = $array' . $keys . ';');
return $result;
}
$keys = '[example][secondDimension][thirdDimension]'; // wrap 1st key with "[" and "]"
echo array_get_value_from_plain_keys($array, $keys);
Learn more about eval() function
if you also want to check if the value is defined or not then you can use this function
function array_check_is_value_set_from_plain_keys($array, $keys)
{
$result;
$keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)
eval('$result = isset($array' . $keys . ');');
return $result;
}
Giving a better name to that function will be appreciated ^^
Here is a solution without using eval:
$array = [
'example' => [
'secondDimension' => [
'thirdDimension' => 'Hello from 3rd dimension',
],
],
];
$keys = '[example][secondDimension][thirdDimension]';
function get_array_value( $array, $keys ) {
$keys = explode( '][', trim( $keys, '[]' ) );
return get_recursive_array_value( $array, $keys );
}
function get_recursive_array_value( $array, $keys ) {
if ( ! isset( $array[ $keys[0] ] ) ) {
return null;
};
$res = $array[ $keys[0] ];
if ( count( $keys ) > 1 ) {
array_shift( $keys );
return get_recursive_array_value( $res, $keys );
} else {
return $res;
}
}
echo get_array_value( $array, $keys );
Want you to use the $b array to follow the nested keys of the $a array and get the value in $c ?
<?php
$a = [ 'key_1' => [ 'key_2' => [ 'key_3' => 'value', ], ], ] ;
$b = ['key_1', 'key_2', 'key_3', ] ;
if ($b)
{
$c = $a ; // $a is not copied (copy-on-write)
foreach($b as $k)
if (isset($c[$k]))
$c = $c[$k] ;
else
{
unset($c);
break;
}
var_dump($c);
}
/*
output :
string(5) "value"
*/
or do you want to generate the $b array for an arbitrary formed string and get $c as a reference ?
<?php
$a = [ 'key_1' => [ 'key_2' => [ 'key_3' => 'value', ], ], ] ;
$b = '[key_1][key_2][key_3]';
if ($b !== '')
{
$b = explode('][', trim($b, '[]'));
$c = &$a ;
foreach($b as $k)
if (isset($c[$k]))
$c = &$c[$k] ;
else
{
unset($c);
break;
}
}
var_dump($c);
$c = 'new val' ;
unset($c);
var_dump($a['key_1']['key_2']['key_3']);
/*
output :
string(5) "value"
string(7) "new val"
*/
You have to use a separate variable for each dimension of the array. A common pattern you see with multidimensional arrays where you need to do something with the 2nd dimension is something like this:
$pets = [
'dog' => ['Jack', 'Fido', 'Woofie'],
'cat' => ['Muggles', 'Snowball', 'Kitty'],
];
// Loop through keys in first dimension
foreach ($pets as $type => $names) {
foreach ($names as $index => $name) {
// And do something with second dimension using the variable
// you've gained access to in the foreach
$pets[$type][$index] = strtoupper($name);
}
}

return array from function php

I need this function to return an array. When I call the function it is printing the array, but when I use return $finalResult in the function, it is only printing the first array.
function readData($file)
{
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach ($textLines as $line)
{
$expLine = explode("\t", $line);
if (count($expLine) < 8)
{
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" => $expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr = $finalResult;
print_r($arr);
}
}
Hi You mush merge or push array to $finalResult see sammple
function readData($file){
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
//Here []
$finalResult[] = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
//$arr=$finalResult;
//print_r($arr);
}
return $finalResult;
}
As described in my comment above
function readData($file){
$arr = array();
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr=array_merge($arr, $finalResult);
}
return $arr;
}

Imploding with "and" in the end?

I have an array like:
Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
It may expand to several more subarrays.
How can I make a list like: TV3+, 6'eren and 5'eren?
As array could potentially be to further depths, you would be best off using a recursive function such as array_walk_recursive().
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
To then convert to a comma separated string with 'and' separating the last two items
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
Took some time but here we go,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
DEMO.
Here you go ,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
if you simply pass in the given array to implode() function,you can't get even the value of the subarray.
see this example
assuming your array name $arr,codes are below
$length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
I think it would work to you:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
Code is "stolen" from here: Implode array with ", " and add "and " before last item
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>

Is it possible to loop array without using foreach?

I have a html array structure..
I output this array with foreach loops. (inside get_output functions)
Is it possible to output results without using foreach?
$schema = array(
array(
'tag' => 'div',
'class' => 'lines',
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
)
);
My function is using foreach loops to output results
function get_output($schema, $t = -2){
$t++; $tag = ""; $atts = array(); $keys = array(); $code = array();
foreach($schema as $k => $v){
if(is_array($v)){
$keys[] = get_output($v, $t);
} else {
switch($k){
case "tag": $tag = $v; break;
case "key": $keys[] = $v; break;
case "type": break;
default: $atts[$k] = $v; break;
}
}
}
if(0 < $t){ $code[] = "\n".str_repeat("\t", $t); }
if($tag){
$code[] = "<$tag"; foreach($atts as $k=>$v){ $code[] = ' '.$k.'="'.$v.'"'; } $code[] = ">";
$code = array(implode('', $code));
}
foreach($keys as $k){ $code[] = $k; }
if($tag){
$code[] = "\n".str_repeat("\t", $t);
$code[] = '</'.$tag.'>';
}
//print_r($code);
return implode("", $code);
}
while and for are perfectly valid ways to loop array:
$a = array(1,2,3); // indexed
$b = array(
'a' => 1,
'b' => 2,
'c' => 3
); // associative
echo '$a indexed with "for": <br />';
for ($i = 0; $i < count($a); $i++) {
echo $a[$i] . '<br />';
}
echo '$a indexed with "while": <br />';
$i = 0; // reset counter
while ($i < count($a)) {
echo $a[$i] . '<br />';
$i++;
}
echo '$b assoc with "for": <br />';
for ($i = 0; $i < count($a); $i++) {
echo key($b) . ' => ' . current($b) . '<br />';
next($b); // step forward
}
echo '$b assoc with "while": <br />';
reset($b); // rewind array cursor to start
while ($value = current($b)) {
echo key($b) . ' => ' . $value . '<br />';
next($b); // step forward
}
Also as you already implemented in your second code snippet, multi-dim array can be looped with recursion (though compared to nested loops it consumes more memory)

Categories