How to echo variable outside of a function? - php

I have this code that echoes values from an array. I'd like to be able to echo the variable elsewhere in my code though. I've tried wrapping a function around it and echoing the function but I can't get anything to work. Here's the code that I have now...
function team(){
if ( ($items = field_get_items('entityform', $entityform, 'field_team_members')) ) {
$values = array_map($items, function($x) { return $x['value']; });
$comma_separated = implode(', ', $values);
foreach ($items as $item) {
$members = $prefix . $item['safe_value'];
$prefix = ', ';
echo $members;
}
}
}
If I simply do team(); it outputs nothing, as well as echo team();. What am I doing wrong here?

Your team function doesn't return anything which is why echo team(); doesn't print anything.
See the documentation on functions for more info: http://php.net/manual/en/functions.returning-values.php
function team(){
$output = '';
if ( ($items = field_get_items('entityform', $entityform, 'field_team_members')) ) {
$values = array_map($items, function($x) { return $x['value']; });
$comma_separated = implode(', ', $values);
$prefix = '';
$members = '';
foreach ($items as $item) {
$members .= $prefix . $item['safe_value'];
$prefix = ', ';
}
$output = $members;
}
return $output;
}

To clarify what i wrote as a comment, i just created a small script:
<?php
function team () {
$string = "hi";
return $string;
}
echo team();

Functions cant work unless until they are called, so you have to call team(); in some way, once called it will for sure display what ever you are trying to echo. Also above function will not display anything unless you force fully exit in that function. Or return some value.

Related

How to get values for multiple keys?

I want to get values using multiple keys.
I have a php code that works for single key but i want to get values for multiple keys. How can i do that?
<?php
$arr=array(
'1'=>'India',
'2'=>'Canada',
'3'=>'United',
'4'=>'China',
'5'=>'London',
'6'=>'New Delhi',
);
$key1='4';
$key2='3';
$key3='4';
echo $arr[$key1, $key2, $key3];
?>
I want output like this in proper order
China
United
China
Thanks in advance.
We have interface ArrayAccess in PHP:
https://www.php.net/manual/en/class.arrayaccess.php
So we can write code as following to support multiple keys( Updated the example from above page ):
You will have to update it to fit your requirements.
<?php
class MultipleKeyArray implements ArrayAccess {
private $container = array();
private $separator = ',';
public function __construct($arr ) {
$this->container = $arr;
}
public function setSeparator($str){
$this->separator = $str;
}
public function offsetSet($offsets, $values) {
$os = explode(',',$offsets);
$vs = explode(',',$values);
$max = max(count($os),count($vs));
for($i=0;$i<$max;$i++){
$offset = $os[$i];
$value = $vs[$i];
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
}
public function offsetExists($offsets) {
$os = explode(',',$offsets);
for($i=0;$i<count($os);$i++){
$offset = $os[$i];
if( !isset($this->container[$offset]) ){
return false;
}
}
return true;
}
public function offsetUnset($offsets) {
$os = explode(',',$offsets);
for($i=0;$i<count($os);$i++){
$offset = $os[$i];
unset($this->container[$offset]);
}
}
public function offsetGet($offsets) {
$os = explode(',',$offsets);
$result = '';
for($i=0;$i<count($os);$i++){
$offset = $os[$i];
$result .= ($i>0 ? $this->separator:'') . (isset($this->container[$offset]) ? $this->container[$offset] : '');
}
return $result;
}
}
$arr=array(
'1'=>'India',
'2'=>'Canada',
'3'=>'United',
'4'=>'China',
'5'=>'London',
'6'=>'New Delhi',
);
$o = new MultipleKeyArray($arr);
$o[] = 'new0';
$o['f,g']='new1,new2';
var_dump(isset($o['f,g']));
var_dump(isset($o['1,2,f']));
var_dump(isset($o['f,not,there']));
echo $o['4,3,4']."\n";
echo $o['2,f,g']."\n";
$o->setSeparator("|");
echo $o['4,3,4']."\n";
Output:
bool(true)
bool(true)
bool(false)
China,United,China
Canada,new1,new2
China|United|China
PHP index cannot take array - you should do that with loop or PHP array function.
First define array of the key you need as:
$keys = [$key1, $key2, $key3];
Now use a foreach loop to echo them as:
foreach($keys as $k)
echo $arr[$k] . PHP_EOL;
And the one-liner:
array_walk($keys, function($k) use ($arr) {echo $arr[$k] . PHP_EOL;});

php replace string type parameter=value

I have a string that comes from a db: $text=
parameter1=value1
parameter2=value2
otherparemeter=othervalue
I need a function to replace an parameter with a new value, but if parameter does not exist; must to add to string;
Example: updatestring ($text,"parameter1","newvalue"):
Result:
parameter1=newvalue
parameter2=value2
otherparemeter=othervalue
Or: updatestring ($text,"myparameter","myvalue"):
Result:
parameter1=value1
parameter2=value2
otherparemeter=othervalue
myparameter=myvalue
thanks !
Given the format of your input parse_ini_string should work to parse out the data into a structure that can easily be altered and reformated.
Maybe something like this:
$a =<<<EOF
parameter1=value1
parameter2=value2
otherparemeter=othervalue
EOF;
function replacevalue($text, $k, $v){
$dat = parse_ini_string($text);
$ret = "";
if(isset($dat[$k])){
$dat[$k] = $v;
foreach($dat as $prop=>$val){
$ret.= $prop."=".$val."\n";
}
return $ret;
}
}
echo replacevalue($a, "parameter1", "Hello World");
this might work if every paramater and value are on its own line
function updatestring($text, $param1, $param2)
{
if( stristr($text, $param1.'=') ) $text = preg_replace("`$param1=.*\n`iU", "$param1=$param2".PHP_EOL, $text);
else $text .= PHP_EOL.$param1.'='.$param2;
return $text;
}
thanks #Orangepill; I've corrected your function; now it's working
function replacevalue($text, $k, $v){
$dat = parse_ini_string($text);
$ret = "";
if(isset($dat[$k])){
$dat[$k] = $v;
} else {
$dat[$k] = $v;
}
foreach($dat as $prop=>$val){
$ret.= $prop."=".$val."\n";
}
return $ret;
}

Access multidimensional array with a path-like string

I have a function called get_config() and an array called $config.
I call the function by using get_config('site.name') and am looking for a way to return the value of $config so for this example, the function should return $config['site']['name'].
I'm nearly pulling my hair out - trying not to use eval()! Any ideas?
EDIT: So far I have:
function get_config($item)
{
global $config;
$item_config = '';
$item_path = '';
foreach(explode('.', $item) as $item_part)
{
$item_path .= $item."][";
$item = $config.{rtrim($item_path, "][")};
}
return $item;
}
This should work:
function get_config($config, $string) {
$keys = explode('.', $string);
$current = $config;
foreach($keys as $key) {
if(!is_array($current) || !array_key_exists($key, $current)) {
throw new Exception('index ' . $string . ' was not found');
}
$current = $current[$key];
}
return $current;
}
you could try something like...
function get_config($item)
{
global $config;
return $config[{str_replace('.','][',$item)}];
}
Inside your get_config function, you can parse the string using explode function in php
function get_config($data){
$pieces = explode(".", $data);
return $config[$pieces[0]][$pieces[1]];
}

PHP -- identifying last key in foreach to eleminate last delimeter

I've been trying to get this to work and while I have tried many methods posted on this site on other pages, I can't get any of them to work.
I need to identify the last key so that my results don't have a , at the end. This sounds like such and easy task but I just cant seem to get it to work! At this point I'm guessing I've just had a typo or something that I overlooked. Any help would be greatly appreciated.
This is what I have:
<?php
$searchString = $_GET["s"];
$prefix = 'http://link_to_my_xml_file.xml?q=';
$suffix = '&resultsPerPage=100';
$file = $prefix . $searchString . $suffix;
if(!$xml = simplexml_load_file($file))
exit('False'.$file);
foreach($xml->results->result as $item) {
echo $item->sku . ",";
}
?>
Now this works just fine, it just has a , at the end:
12345,23456,34567,45678,
For reference my xml file is laid out like: results->result->sku, but with a lot more mixed in. I'm just singling out the fields.
Consider identifying the first instead?
$first = true;
foreach($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ',';
}
echo $item->sku;
}
Use rtrim()
foreach($xml->results->result as $item) {
$mystr .= $item->sku . ",";
}
echo rtrim($mystr, ",")
Should output:
12345,23456,34567,45678
Demo!
If your keys are in numerical order like: 0, 1, 2, 3 etc this could be a solution:
foreach($xml->results->result as $key => $item)
{
if( $key > 0 ) echo ", ";
echo $item->sku
}
Possible solution #1:
$first = true;
foreach ($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ', ';
}
echo $item->sku;
}
Possible solution #2:
$items = array();
foreach ($xml->results->result as $item) {
$items[] = $item->sku;
}
echo join(', ', $items);
You can just put everything in a string and then run:
substr($yourstr, 0, -1);
on your code to remove the last character:
http://de1.php.net/manual/en/function.substr.php
Or get the total number of entries in your array and count your position

Process an array in a function, with external formatting

I want to pass an array to a function and iterate through it in this function. But I would like to be able to change the way the single entries are displayed.
Suppose I have an array of complicated objects:
$items = array($one, $two, $three);
Right now I do:
$entries = array();
foreach($items as $item) {
$entries[] = create_li($item["title"], pretty_print($item["date"]));
}
$list = wrap_in_ul($entries);
I would like to do the above in one line:
$list = create_ul($items, $item["title"], pretty_print($item["date"]));
Any chance of doing that as of PHP4? Be creative!
from my understanding, you're looking for an "inject" type iterator with a functional parameter. In php, inject iterator is array_reduce, unfortunately it's broken, so you have to write your own, for example
function array_inject($ary, $func, $acc) {
foreach($ary as $item)
$acc = $func($acc, $item);
return $acc;
}
define a callback function that processes each item and returns accumulator value:
function boldify($list, $item) {
return $list .= "<strong>$item</strong>";
}
the rest is easy:
$items = array('foo', 'bar', 'baz');
$res = array_inject($items, 'boldify', '');
print_r($res);
You could use callbacks:
function item_title($item) {
return $item['title'];
}
function item_date($item) {
return $item['date'];
}
function prettyprint_item_date($item) {
return pretty_print($item['date']);
}
function create_ul($items, $contentf='item_date', $titlef='item_title') {
$entries = array();
foreach($items as $item) {
$title = call_user_func($titlef, $item);
$content = call_user_func($contentf, $item);
$entries[] = create_li($title, $content);
}
return wrap_in_ul($entries);
}
...
$list = create_ul($items, 'prettyprint_item_date');
PHP 5.3 would be a big win here, with its support for anonymous functions.

Categories