dynamic creation of php code from array in php - php

I have a code to generate php code from an array of words, however the list of words is variable
like:
$list=array(
"BMW",
"MUSTANG",
"DBM",
"Txt62"
);
$arrlength=count($list);
for($x=0;$x<$arrlength;$x++)
{
echo ' \'' .$list[$x]. '\'' . ' => $this->input->post("'.$list[$x].'") == \'\' ? \'Not defined definido\' : $this->input->post("'.$list[$x].'"), ';
echo "<br>";
}
Is there a better way to do it, like a function that I pass the array of words, and it returns php code?, Is this possible inside php code?

It's not easy to understand what you're trying to do, but if it is to run a function on every item in an array, you can use array_walk for that ?
$list = array(
"BMW",
"MUSTANG",
"DBM",
"Txt62"
);
function validate($item, $key) {
echo ' \'' .$item. '\'' . ' => $this->input->post("'.$item.'") == \'\' ? \'Not defined definido\' : $this->input->post("'.$item.'"), <br>';
}
array_walk($list, 'validate');

Related

Implode with default value if no values

I want to show dash(-) if my array is empty after imploding it. Here below is my try so far.
Result with Data in Array -> https://repl.it/HIUy/0
<?php
$array = array(1,2);
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data - ' . implode(',', $result);
//Result : Array With Data : 1,2
?>
Result without Data in Array -> https://repl.it/HIVE/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array Without Data - ' . implode(',', $result);
//Result : Array With Data - :
?>
As you can see in the second result, I am unable to print anything as my array was blank hence I was unable to print anything.
However, I want to print Dash(-) using implode only by using something like array_filter which I already tried but I am unable to do so. Here I have tried this https://repl.it/HIVP/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data : ' . implode(',', array_filter($result));
//Result : Array With Data :
?>
Can someone guide me how to achieve this ?
Thanks
You can check if your array is empty and then return/ echo a Dash:
if(!empty($array)){
// Array contains values, everything ok
echo 'Array with data - ' . implode('yourGlueHere', $array);
} else {
// Array is empty
echo 'Array without data -';
}
If you want to have it in one line, you could do something like the following:
echo 'Array with' . empty($array) == false ? '' : 'out' . 'data - ' . empty($array) == false ? implode('glue', $array) : '';
Answers posted by Tobias F. and Gopi Chand is correct.
Approach 1:
I'd suggest you going this way would help you (Basically using ternary operator).
As here is no other way of doing this using just implode function.
echo empty($result) ? '-' : implode(',',$result);
Approach 2
Using a helper function like this.
function myImpllode($glue = "", $array = [])
{
if(!empty($array)){
// Array contains values, everything ok
return implode($glue, $array);
} else {
// Array is empty
return '-';
}
}

PHP array runs function and pass variable to it

I am coding a bot for a game and I am now coding the handlers I want to call my array so it runs the function.
$handlers = array(
"x" => function()
);
function function($m)
{
echo "Var: " . $m . "\n";
}
When I call handlers I tried it like this:
$handlers("x");
So how can I pass the variable to the function.
What you need is the call_user_func function. Besides, in your $handlers array, the name of the function must be in quotation marks and you can not use the reserved keyword function as the name of the function! and you may access the array element using [] operator:
$handlers = array(
"x" => '_function'
);
function _function($m)
{
echo "Var: " . $m . "\n";
}
call_user_func($handlers['x'], "hello :)");
For completeness, you can do it this way as well:
$handlers = array(
"x" => 'test'
);
function test($m) {
echo "Var: " . $m . "\n";
}
$handlers['x']("testing...");

best way to pass a variable number of arguments to a php function

What is the best way to pass a variable number of arguments to a php function? I mean, suppose i have the following:
function my_func($a, $b, $c) {
$q = 'SELECT ' . $a . ' FROM ' . $b . ' WHERE status IS NULL';
}
my_func('id', 'table');
my_func('id', 'table', ' AND x = 1');
I've read about func_get_arg(), but if i call func_get_arg(2) in the first situation, i will get a, Argument 2 not passed to function error.
IMPORTANT: this query is not performed with user-passed arguments, so no injection hazzards! It is performed with controlled arguments given by me and its function is to check if that value is valid within a combination of foreign keys! So please no sarcastic 'injection paradise' comments, thank you.
Well i do not know if it's best, but i like to pass the array as argument and then work with it in my function. Here is one example:
function my_query($query = array())
{
// select and from are required to exist
if(!empty($query) && array_key_exists('select', $query) && array_key_exists('from', $query))
{
$q = "select {$query['select']}";
$q .= " from {$query['from']}";
foreach($query as $key => $val)
{
// Don't want to include select and from once again (also do not unset before in case need to run all of this once again)
if($key != 'select' && $key != 'from')
{
// Search if key has underscore and replace it with space for valid query
if(strpos($key, '_') !== false)
$key = str_replace('_', ' ', $key);
// Build query with spaces and all
$q .= " " . $key . " " . $val;
}
}
// Run query here using $q
}
}
And you can pass in array as you like:
$query = array(
'select' => '*',
'from' => 'users',
'where' => 'age > 25',
'order by' => 'id'
);
// Or
$query = array();
$query['select'] = '*';
$query['from'] = 'users';
$query['where'] = 'age > 25';
$query['order_by'] = 'id';
my_query($query);
// Would return us something like this
string(46) "select * from users where age > 25 order by id"
But using this you have to maintain right order in your array or write ordering and validation code in your function.
Since you have mentioned that your function does not deal with user-passed arguments.. I am suggesting this..
FYI : I just used an echo inside that for demonstration purposes.. you can change that later.
<?php
function my_func() {
echo $q = 'SELECT ' . func_get_arg(0) . ' FROM ' . func_get_arg(1) . ' WHERE status IS NULL';
}
my_func('id', 'table');
The above displays...
SELECT id FROM table WHERE status IS NULL
The arguments start from 0 index, so you should probably do.. func_get_arg(1) to get the second argument.

Why do I get "Undefined variable" when trying to resolve a multi-dimensional array?

I'm trying to retrieve an item from a multi-dimensional array through a string that describes the path into the array (like first.second.third).
I've chosen the approach as shown here (also available on ideone):
<?php
// The path into the array
$GET_VARIABLE = "a.b.c";
// Some example data
$GLOBALS["a"]= array("b"=>array("c"=>"foo"));
// Construct an accessor into the array
$variablePath = explode( ".", $GET_VARIABLE );
$accessor = implode( "' ][ '", $variablePath );
$variable = "\$GLOBALS[ '". $accessor . "' ]";
// Print the value for debugging purposes (this works fine)
echo $GLOBALS["a"]["b"]["c"] . "\n";
// Try to evaluate the accessor (this will fail)
echo $$variable;
?>
When I run the script, it will print two lines:
foo
PHP Notice: Undefined variable: $GLOBALS[ 'a' ][ 'b' ][ 'c' ] in ...
So, why does this not evaluate properly?
I think the $$ notation only accepts a variable name (ie. the name of a variable). You are actually trying to read a variable named "$GLOBALS[ 'a' ][ 'b' ][ 'c' ]", which does not exist.
As an alternative ($GET_VARIABLE seems to be your input string), you could try this:
$path = explode('.', $GET_VARIABLE);
echo $GLOBALS[$path[0]][$path[1]][path[2]];
Wrap this in a suitable loop to make it more dynamic; it seems to be trivial.
It looks like PHP is treating your entire string like a variable name, and not as an array.
You could try using the following approach instead, as it would also probably be simpler.
<?php
// The path into the array
$GET_VARIABLE = "a.b.c";
// Some example data
$GLOBALS["a"]= array("b"=>array("c"=>"foo"));
// Construct an accessor into the array
$variablePath = explode( ".", $GET_VARIABLE );
//$accessor = implode( "' ][ '", $variablePath );
//$variable = "\$GLOBALS[ '". $accessor . "' ]";
// Print the value for debugging purposes (this works fine)
echo $GLOBALS["a"]["b"]["c"] . "\n";
// Try to evaluate the accessor (this will fail)
echo $GLOBALS[$variablePath[0]][$variablePath[1]][$variablePath[2]];
?>
Here's some code I wrote to access $_SESSION variables via dot notation. You should be able to translate it fairly easily.
<?php
$key = "a.b.c";
$key_bits = explode(".", $key);
$cursor = $_SESSION;
foreach ($key_bits as $bit)
{
if (isset($cursor[$bit]))
{
$cursor = $cursor[$bit];
}
else
{
return false;
}
}
return $cursor;
Here's one more solution using a helper function:
function GetValue($path, $scope = false){
$result = !empty($scope) ? $scope : $GLOBALS;
// make notation uniform
$path = preg_replace('/\[([^\]]+)\]/', '.$1', $path); // arrays
$path = str_replace('->', '.', $path); // object properties
foreach (explode('.', $path) as $part){
if (is_array($result) && array_key_exists($part, $result)){
$result = $result[$part];
} else if (is_object($result) && property_exists($result, $part)){
$result = $result->$part;
} else {
return false; // erroneous
}
}
return $result;
}
And example usage:
// Some example data
$GLOBALS["a"] = array(
'b' => array(
'c' => 'foo',
'd' => 'bar',
),
'e' => (object)array(
'f' => 'foo',
'g' => 'bar'
)
);
$bar = array(
'a' => $GLOBALS['a']
);
echo $GLOBALS['a']['b']['c'] . "\n"; // original
// $GLOBALS['a']['b']['c']
echo GetValue('a.b.c') . "\n"; // traditional usage
// $GLOBALS['a']['b']['c']
echo GetValue('a[b][c]') . "\n"; // different notation
// $bar['a']['b']['c']
echo GetValue('a.b.c', $bar) . "\n"; // changing root object
// $GLOBALS['a']['e']->f
echo GetValue('a[e]->f') . "\n"; // object notation

PHP array to jQuery options

I'm creating a Wordpress Plugin which uses a jQuery script. I've created a PHP array which contains its options like:
$settings = array('setting1' => 'value1', 'setting2' => 'value2', 'setting3' => 10)
I was now going to use foreach to loop over the items and print them like this:
foreach($settings as $setting => $value) {
if (is_string($value)) { $value = "'" . $value . "'"; }
$output .= $setting . ':' . $value .',';
}
which should make me end up with:
(window).load(function() {
$('#widget').myWidget({
setting1:'value1',
setting2:'value2',
setting3:10})
With the current setup I end up with the last entry having a ',' at the end (one too many) which means I get a Javascript error, so I need to remove it.
All with all, I have the feeling I'm doing something very dirty (including the is_string check) and I was wondering if there is a neat way to deal with this?
There is a json_encode function if you're using PHP >= 5.2
You should use json_encode() for this. It does all the dirty work for you.
(window).load(function() {
$('#widget').myWidget(
<?php echo json_encode($settings); ?>
);
}
Have you tried json_encode ?
Exemple from the docs:
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Would output
{"a":1,"b":2,"c":3,"d":4,"e":5}
Here's a little thing I like to use when dealing with situations like this. I know it doesn't really answer your question, but it is an elegant way of solving the comma problem.
$comma = '';
foreach($settings as $setting => $value) {
if (is_string($value)) {
$value = "'" . $value . "'";
$output .= $comma . $setting . ':' . $value;
$comma = ',';
}
}
So on the first run $comma is blank, but after that it gets put between every new entry.

Categories