Is there a php function that mimics the " " behavior? - php

i'm trying to create a table view helper in Zend Framework , it takes an array of models and generate an html table that displays the model properties.
The user can add extra columns to display operations like update ,delete models ,.
so the user can add a string like that
$columnContent = '<a href=\'update/$item[id]\'>update</a>' ;
note that i use simple quotes to cache the string to be evaluated later
my problem is , is there a way to evaluate that string in a context , later on ?
so i need to mimic the " " behavior of strings in Php , thanks.
something like :
// in the context , where $item is a row of an array of models :
$myVar = evaluatemyString($columnContent);
EDIT :
i'm not looking for the eval function which doesnt work in my case , ( i think ).
EDIT 2 :
i need to put the result of the in a variable too.

The eval function in PHP
eval($columnContent);

Use "templates" (the quotes are intended) instead. Have a look at intl, especially messageformatter. Also there are the good old printf()-functions (inlcuding sprintf() and so on)

Here is a simple UTF-8 safe string interpolation example. The regular expression forces variables with the following rules:
Prefixed with #
object:property notation (denotes an associative array key "object" whose value is also an associative array)
In other words, instead of variables like: $item[id]
You will have variables like: #user:id
<?php
// update
//$template = 'update';
// update
$template = 'update';
// fixture data
$db[499] = array('user' => array('id' => 499));
$db[500] = array('user' => array('id' => 500));
// select record w/ ID = 500
$context = $db[500];
// string interpolation
$merged = preg_replace_callback('/#(?:(?P<object>[^:]+):)(?P<property>[\w][\w\d]*){1}/iu', function($matches) use($context) {
$object = $matches['object'];
$property = $matches['property'];
return isset($context[$object][$property])
? $context[$object][$property]
: $matches[0];
}, $template);
echo "TEMPLATE: ${template}", PHP_EOL;
echo "MERGED : ${merged}", PHP_EOL;

Related

String pass as array in andFilterWhere() in Yii2

One String like below:
$condition = "['or',['LIKE','name','index'],['=','type',1]]";
get condition string from Database
want to convert in array so, it can pass in below statement:
$query->andFilterWhere($condition);
You could simply use eval() (not specific to yii) :
$condition = "['or',['LIKE','name','index'],['=','type',1]]";
eval("\$condition = $condition;");
Read more about eval().

Dynamically created Variables in PHP produce occasionally names like "_GET" or "_POST" instead of the variable names

I have a function from which I call many different variables, and produce another (dynamically created) return variable.
All good. (I explain my Problem below this PHP 5.3 example)
function showArrayIntersection($ar1, $ar2) {
$dynamicName = array_search($ar1, $GLOBALS) . '_' . array_search($ar2, $GLOBALS);
global ${$dynamicName};
${$dynamicName} = implode(array_values(array_intersect($ar1, $ar2)));
}
$Bankers = [6,7,0,6,5,6,2]; // `[]` is equivalent to `array()` introduced in PHP 5.4
$Bond = [6,7,0,5,0];
$Politicians = [4,6,1,6,4,6,3];
$James = [0,1,0,3,7];
showArrayIntersection($James, $Bond);
showArrayIntersection($Bankers, $Politicians);
echo "Moneysystem: $Bankers_Politicians\n";
echo "Moneypenny : $James_Bond\n";
Output:
Moneysystem: 666
Moneypenny : 007
This works most of the time well, but sometimes only instead of a variable name like $James_Bond I get a variable name like POST_POST or GET_GET, meaning instead of the name James or Bond PHP returns either a "_GET" or a "_POST".
Since AbraCadaver asked full of solicitousness: "What in the world are you doing?"
here my solution and explanation:
Einacio: I coudn't create the names on the fly because the already arrive from a first function dynamically, so the actual variable name is not the true name.
And AbraCadaver pointed out that array_search() does not accept an array; unfortunately for sake of brevity I omitted that I pass on as a first argument not an array but another dynamic created variable from the root - I didn't want to make it too complicated, but basically it works like this:
function processUsers ($userName , $request2send ){
global ${$user.'_'.$request2send};
$url2send = "http...?request=".$request2send ;
...
$returnedValue = receivedDataArray ();//example elvis ([0] => Presley );
${$user.'_'.$request2send} = $returnedValue;
}
--- now Now I get the value of the function in the root ---
$firstValue = processUsers ("cuteAnimal" , "getName");
// returns: $cuteAnimal_getName = "Mouse"
and
$secondValue = processUsers ("actorRourke" , "getFirstName");
// returns: $actorRourke_getFirstName = "Mickey";
And now the bummer - a second function which needs the first one to be completed:
function combineValues ($firstValue , $secondValue ){
global ${$firstValue.'AND'.$secondValue};
${$firstValue.'_'.$secondValue} = $firstValue." ".$secondValue;
}
// returnes $actorRourke_getFirstNameANDcuteAnimal_getName = "Mickey Mouse";
Of course the second function is much more complicated and requires first to be completed,
but I hope you can understand now that it is not an array directly which I passed on but dynamic variable names which I could not just use as "firstValue" but I needed the name "actorRourke_getFirstName".
So AbraCadaver's suggestion to use $GLOBALS[..] did not work for me since it requires arrays.
However: Thanks for all your help and I hope I could now explain the issue to you.
Argument 1 for array_search() does not accept an array.
print_r($GLOBALS); will show the empty $_GET and $_POST arrays.
What in the world are you doing?
To go with Einacio:
function showArrayIntersection($ar1, $ar2) {
$GLOBALS[$ar1 . '_' . $ar2] = implode(array_intersect($GLOBALS[$ar1], $GLOBALS[$ar2]));
}
showArrayIntersection('James', 'Bond');
echo "Moneypenny : $James_Bond\n";
You could check to make sure they exist of course isset().
how about just using the names of the variables? it would also avoid value conflicts
function showArrayIntersection($ar1, $ar2) {
$dynamicName = $ar1 . '_' . $ar2;
global ${$dynamicName};
${$dynamicName} = implode(array_values(array_intersect($_GLOBALS[$ar1], $_GLOBALS[$ar2])));
}
$Bankers = [6,7,0,6,5,6,2]; // `[]` is equivalent to `array()` introduced in PHP 5.4
$Bond = [6,7,0,5,0];
$Politicians = [4,6,1,6,4,6,3];
$James = [0,1,0,3,7];
showArrayIntersection('James', 'Bond');
showArrayIntersection('Bankers', 'Politicians');
echo "Moneysystem: $Bankers_Politicians\n";
echo "Moneypenny : $James_Bond\n";

Get string from array via property lookup, but insert a variable

I want to use property look-up on an associative array of strings, but there's a catch - I need to be able to use a variable in the string. I came up with two solutions, but both seem hacky in PHP.
$foo = [
'someProp' => 'Some value here: $$value$$.'
];
$myProp = 'someProp';
$value = 'some value';
$myString = $foo[$myProp];
$myString = str_replace('$$value$$', $value, $myString);
echo $myString;
In JavaScript, I would probably use functions instead of strings and return the string including the variable. I've heard that this is bad practice in PHP.
$foo = array(
'someProp' => function($value) {
return "Some value here: {$value}.";
}
);
$myProp = 'someProp';
$value = 'some value';
$myString = $foo[$myProp]($value);
echo $myString;
To be sure this is not an X/Y problem, I will say that my goal is to abstract my error messages to one location in my code (the array mentioned here) and form what might be considered an error api for use throughout the application. For example:
try {
something(); //throws "MyException('someProp', 'someValue');
}
catch (MyException $e) {
$someClass->addError($e->getType(), $e->getValue());
//this function will get the string based on $type and add $value to it, then add the message to an array
}
Are either of these two approaches the way to go? The answer I'm looking for would include a more optimum solution if there is one and mature thoughts on my two proposed solutions.
From your example, is there only a single variable per message string or it could be many variables?
If there's only single variable, instead of role out your old string interpolation, you could use sprinf for this. This is more flexible in my opinion since it allows you to do many formatting types e.g. int, decimal etc
$foo = [
'someProp' => 'Some value here: %s.'
];
$myString = sprintf($myString, $value);

code igniter form_input

A couple questions here..
What is the following syntax?
What do all the pieces mean?
(( ! is_array($data)) ? $data : '')
How is it used in the function at the end?
function form_input($data = '', $value = '', $extra = '')
{
$defaults = array('type' => 'text', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);
return "<input "._parse_form_attributes($data, $defaults).$extra." />";
}
Thankyou. Blake
Ok let me try as far as I understand you question.
What is the following syntax?
It is a function definition.
What do all the pieces mean?
This is the ternary operator. It means: If $data is not an array (!is_array($data)), return $data (? $data) otherwise return an empty string (: '')
It is a shorthand for if-else.
How is it used in the function at the end?
Not sure what you mean here. A function _parse_form_attributes($data, $defaults) is called witch seems to return a string.
If it in your question refers to $defaults, then it is just an array that gets build and that contains the following values:
Array (
'type' => 'text',
'name' => $data, // or empty string if $data is an array,
'value' => $value
);
It is used to build an input element, that will look like this:
<input type="text"
name="(value of $data or empty)"
value="(value of $value)"
(value of $extra)
/>
Ok this seems to generate the HTML for a form input with ome useful default values.... To answer your Qs in order:
It's a function that takes optional parameters. You could call eg form_input('SomeData', 'SomeValue');
It creates the HTML for the element and includes whatever information you give it, using defaults if no value is provided
A difficult one to answer... In short you're defining a new function. If you provide parameters, they will be used to create a form element. If you omit them, defaults will be used - eg type will default to text for output like <input type="text" [blah]>
I'm not quite sure what you mean here - Append as key-value pairs eg <input type="text" key="Value" [blah]> ? If this is the case, I would personally lose the $extra variable and have an array of key->value pairs instead. Failing that, you need to et $extra as appropriate eg key1="value1" key2="value2"
It's an inline expression of:
function form_input($data = '', $value = '', $extra = '')
{
if (is_string($data)) { // or better: is_scalar()
// leave as-is
}
else {
$data = '';
}
...
(Slightly variated.)
It basically ensures that the $data parameter is never an array. Maybe it was allowed to be an array in previous versions of the function, and this is safety code to ensure correct operation.
Note that type enforcement is another approach (often overkill, but sometimes advisable):
function xy($data, $value, $z) {
assert( ! is_array($data) );
assert( is_string($value) );
1) It returns an input field;
2) Pardon?
3) Function takes three values. $value is the default value of the input field (the one you find in the textbox); $data will be the name of the form if it isn't an array, otherwise the name will be blank; $extra is a string containing other stuff that will go in the form. Please refer to the function _parse_form_attributes;
4) link
By the way, I sincerely hope that _parse_form_attributes() does something amazing, since that looks like an incredibly verbose function and codeigniter has some handy built-in form generation functions.

Need Help With PHP Function, It doesn't work when i pass value by variable

Here's a php function and it works perfectly.
$values = array(
'php' => 'php hypertext processor',
'other' => array(
'html' => 'hyper text markup language',
'css' => 'cascading style sheet',
'asp' => 'active server pages',
)
);
function show($id='php', $id2='') {
global $values;
if(!empty($id2)) {
$title = $values[$id][$id2];
}
else {
$title = $values[$id];
}
echo $title;
}
When i execute this <?php show(other,asp); ?> it displays active server pages and it works, but when i do it this way it shows an error
<?php
$lang = 'other,asp'
show ($lang);
?>
It doesn't work., Please help me out here
P.S : It works if i pass variable with single value (no commas)
If you'd like to pass it in the way you have it,
maybe try using explode:
function show($id='php') {
global $values;
$ids = explode(',',$id);
if(!empty($ids[1])) {
$title = $values[$ids[0]][$ids[1]];
}
else {
$title = $values[$ids[0]];
}
echo $title;
}
You can't pass two variables in one string. Your string $lang needs to be split up into two vairables:
$lang1 = 'other';
$lang2 = 'asp';
show($lang1, $lang2);
It fails because the key "other,asp" doesn't exist in $values.
In other words, it is trying to evaluate the following:
$title = $values['other,asp'];
PS, it's always useful to provide an actual error rather than saying "it doesn't work".
This is because $lang will get interpreted as a single argument, so $id2 will be 'other,asp'. You need to pass them into the function separately:
$id1 = 'other';
$id2 = 'asp';
show($id1,$id2);
P.S : It works if i pass variable with single value (no commas)
You are assigning $lang to the value 'other,asp', and then passing that sole $lang variable to the show function. There is no key named "other,asp" in your $values array.
Having a comma in the string doesn't mean you're splitting the parameters, it means you're passing a single string value. You have to "pass a variable with a single value", or do it like this for multiple parameter values:
$lang = "other";
$sub_lang = "asp";
show ($lang, $sub_lang);
You are returning one string instead of the two required... how about rewriting your function to handle them instead?

Categories