I want to create a php function with the following code but when I add this to a function it stops working:
Code works:
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
Code Doesnt work:
function metaData() {
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
}
metaData(); // NULL
$home, $about, and $details are all out of scope in your function. You need to pass them as parameters to that function for them to be available to the function itself.
function metaData($home, $about, $details) {
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
}
metaData($home, $about, $details);
Related
I have a small problem with my recursive function, and it is that FQDN is not being created correctly.
public function testBuildReverseSchemaNames() {
$input = [
'propertyZeroSchema' => 'value_0',
'communicationPreferences' => [
'grv3_newsletter_bi' => true
],
'someContainer' => [
'propertyOneSchema' => 'value_1'
],
'propertyThreeSchema' => 'value_3'
];
$expected = [
'propertyZeroSchema' => 'value_0',
'communicationPreferences.grv3_newsletter_bi' => true,
'someContainer.propertyOneSchema' => 'value_1',
'propertyThreeSchema' => 'value_3'
];
$output = [];
$this->buildReverseSchemaNames($input, $output);
$this->assertEquals($expected, $output);
}
public function buildReverseSchemaNames($data, &$output, $currentFqdn = '') {
foreach ($data as $key => $value) {
if (is_array($value)) {
$currentFqdn .= $key.'.';
$this->buildReverseSchemaNames($value, $output, $currentFqdn);
} else {
$currentFqdn .= $key;
$output[$currentFqdn] = $value;
}
}
}
But the output is like this:
Array (
'propertyZeroSchema' => 'value_0'
'propertyZeroSchemacommunicationPreferences.grv3_newsletter_bi' => true
'propertyZeroSchemacommunicationPreferences.someContainer.propertyOneSchema' => 'value_1'
'propertyZeroSchemacommunicationPreferences.someContainer.propertyThreeSchema' => 'value_3'
)
Well, I was able to find the answer by myself:
Edit: After I thought about doing it cleaner, #jh1711 just answered this. If you repost it I will accept your answer.
public function buildReverseSchemaNames($data, &$output, $currentFqdn = '') {
foreach ($data as $key => $value) {
if (is_array($value)) {
$this->buildReverseSchemaNames($value, $output, $currentFqdn . $key.'.');
} else {
$output[$currentFqdn.$key] = $value;
}
}
}
You should not modify $currentFqdn inside your function. Otherwise your changes will affect later iteration of the foreach loop. It should work, if you modify your code like this:
public function buildReverseSchemaNames($data, &$output, $currentFqdn = '') {
foreach ($data as $key => $value) {
if (is_array($value)) {
$this->buildReverseSchemaNames($value, $output, $currentFqdn.$key.'.');
} else {
$output[$currentFqdn.$key] = $value;
}
}
}
I am new to web programming and I have such a complex posts all over my work this was the result for a var_dump($_POST) , I am using gettype() function to determine that if the value in the $arr array is another array or not , I am not convenient of such behave of code of mine , neither the problems that I always met when going to loop for insertion
the question is if there is smarter technique to loop within like this complex posts , secondly how to catch the name,phone in the 2d array that called assistant (called assistant['name'],assistant[phone])
<?php
$arr = array(
"name"=> "mmmkkkk",
"phones"=> array(
"01553338897" ,
"09090909098"
),
"address"=> "107 ostras., Germany",
"assistant"=> array(
"name" => array(
"kmkkm",
"komar"
),
"phone"=> array(
"01043338897" ,
"09099090090"
)
)
);
foreach($arr as $key => $p_value)
{
if(gettype($p_value)=="array")
{
echo $key.":"."</br>";
foreach($p_value as $newp_value => $val )
{
if(gettype($val)=="array")
{
foreach($val as $vkey)
{
echo $vkey."</br>";
}
}
else{echo $val."</br>";}
}
}else{echo $key.":".$p_value."</br>";}
}
?>
You can use Recursive function like this.
<?php
$arr = array(
"name"=> "mmmkkkk",
"phones"=> array(
"01553338897" ,
"09090909098"
),
"address"=> "107 ostras., Germany",
"assistant"=> array(
"name" => array(
"kmkkm",
"komar"
),
"phone"=> array(
"01043338897" ,
"09099090090"
)
)
);
function rec($arr) {
foreach($arr as $key => $p_value)
{
if (is_array($p_value)) {
rec($p_value);
} else {
echo $key.":".$p_value."\n";
}
}
}
rec($arr);
?>
Think recursive
function walkThrough($array, $tabulation = 0) {
foreach($array as $key => $value) {
printf ('%s%s:', str_repeat(4*$tabulation, ' '));
if (is_array($value)) walkThrough ( $value, ($tabulation+1) );
else printf('%s<br />', $value);
}
}
Use this Recursive function
function recursivefunc($arr,$key =''){
if(is_array($arr)){
foreach($arr as $k => $v){
if (is_array($v) && !empty($v)) {
recursivefunc($v,$k);
} else {
$keys = ($key=='') ? $k : $key;
echo $keys.":".$v.'</br>';
}
}
}
}
recursivefunc($arr);
Out put :
name:mmmkkkk
phones:01553338897
phones:09090909098
address:107 ostras., Germany
name:kmkkm
name:komar
phone:01043338897
phone:09099090090
I've realized I need to stop banging my head and ask for help...
I have the following array:
$permissionTypes = array(
'system' => array(
'view' => 'View system settings.',
'manage' => 'Manage system settings.'
),
'users' => array(
'all' => array(
'view' => 'View all users.',
'manage' => 'Manage all users.'
)
),
'associations' => array(
'generalInformation' => array(
'all' => array(
'view' => 'View general information of all associations.',
'manage' => 'Manage general information of all associations.'
),
'own' => array(
'view' => 'View general information of the association the user is a member of.',
'manage' => 'Manage general information of the association the user is a member of.'
)
)
));
I'm trying to collapse / cascade the keys into a one-dimension array like so:
array(
'system_view',
'system_manage',
'users_all_view',
'users_all_manage',
'associations_generalInformation_all_view',
'associations_generalInformation_all_manage',
'associations_generalInformation_own_view',
'associations_generalInformation_own_manage'
)
I could use nested loops, but the array will be an undefined number of dimensions.
This is the closest I've gotten:
public function iterateKeys(array $array, $joiner, $prepend = NULL) {
if (!isset($formattedArray)) { $formattedArray = array(); }
foreach ($array as $key => $value) {
if(is_array($value)) {
array_push($formattedArray, $joiner . $this->iterateKeys($value, $joiner, $key));
} else {
$formattedArray = $prepend . $joiner . $key;
}
}
return $formattedArray;
}
Any ideas?
I think this should do it:
public function iterateKeys(array $array, $joiner, $prepend = NULL) {
if (!isset($formattedArray)) {
$formattedArray = array();
}
foreach ($array as $key => $value) {
if(is_array($value)) {
$formattedArray = array_merge($formattedArray, $this->iterateKeys($value, $joiner, $prepend . $joiner . $key));
} else {
$formattedArray[] = $prepend . $joiner . $key;
}
}
return $formattedArray;
}
Since the recursive call returns an array, you need to use array_merge to combine it with what you currently have. And for the non-array case, you need to push the new string onto the array, not replace the array with a string.
try this:
function flattern(&$inputArray, $tmp = null, $name = '')
{
if ($tmp === null) {
$tmp = $inputArray;
}
foreach($tmp as $index => $value) {
if (is_array($value)) {
flattern($inputArray, $value, $name.'_'.$index);
if (isset($inputArray[$index])) {
unset($inputArray[$index]);
}
} else {
$inputArray[$name.'_'.$index] = $value;
}
}
return $inputArray;
}
var_dump(flattern($permissionTypes));
function flattenWithKeys(array $array, array $path = []) {
$result = [];
foreach ($array as $key => $value) {
$currentPath = array_merge($path, [$key]);
if (is_array($value)) {
$result = array_merge($result, flattenWithKeys($value, $currentPath));
} else {
$result[join('_', $currentPath)] = $value;
}
}
return $result;
}
$flattened = flattenWithKeys($permissionTypes);
Working fine for me.
function array_key_append($source_array, $return_array = array(), $last_key = '', $append_with = "#")
{
if(is_array($source_array))
{
foreach($source_array as $k => $v)
{
$new_key = $k;
if(!empty($last_key))
{
$new_key = $last_key . $append_with . $k;
}
if(is_array($v))
{
$return_array = array_key_append($v, $return_array, $new_key, $append_with);
} else {
$return_array[$new_key] = $v;
}
}
}
return $return_array;
}
$StandardContactRequestDataforALL = array_key_append($StandardContactRequestDataforALL, $return_array = array(), $last_key = '', $append_with = "#");
I searched in Google and consulted the PHP documentation, but couldn't figure out how the following code works:
$some='name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
return $addons;
}
echo (count( getActiveAddons( $some ) ) ? implode( '<br />', getActiveAddons( $some ) ) : 'None');
The code always echo's None.
Please help me in this.
I don't know where you got this code from but you've initialized $some the wrong way. It is expected as an array like this:
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon'
'nextduedate' => '2013-04-11',
'status' => 'Active'
)
);
I guess the article you've read is expecting you to parse the original string into this format.
You can achieve this like this:
$string = 'name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
$result = array();
foreach(explode('|', $string) as $record) {
$item = array();
foreach(explode(';', $record) as $column) {
$keyval = explode('=', $column);
$item[$keyval[0]] = $keyval[1];
}
$result[]= $item;
}
// now call your function
getActiveAddons($result);
$some is not an array so foreach will not operate on it. You need to do something like
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon',
'nextduedate' => '2013-04-11',
'status'=> 'Active'
)
);
This will create a multidimensional array that you can loop through.
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
foreach($addon as $key => $value) {
if ($key == 'status' && $value == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
}
return $addons;
}
First, your $some variable is just a string. You could parse the string into an array using explode(), but it's easier to just start as an array:
$some = array(
array(
"name" => "Licensing Module",
"nextduedate" => "2013-04-10",
"status" => "Active",
),
array(
"name" => "Test Addon",
"nextduedate" => "2013-04-11",
"status" => "Active",
)
);
Now, for your function, you are on the right track, but I'll just clean it up:
function getActiveAddons($somet) {
if (!is_array($somet)) {
return false;
}
$addons = array();
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
}
}
if (count($addons) > 0) {
return $addons;
}
return false;
}
And finally your output (you were calling the function twice):
$result = getActiveAddons($some);
if ($result === false) {
echo "No active addons!";
}
else {
echo implode("<br />", $result);
}
I'm sure there is a better to this. Any help will be greatly appreciated.
I want to pass an array to a php function that contains the argument and all the arguments are optional. I'm using code ignitor and am by no means an expert. Below is what i have been using so far:
function addLinkPost($postDetailArray) {
if (isset($postDetailArray['title'])) {
$title = $postDetailArray['title']; }
else {
$title = "Error: No Title";
}
if (isset($postDetailArray['url'])) {
$url = $postDetailArray['url'];
} else {
$url = "no url";
}
if (isset($postDetailArray['caption'])) {
$caption = $postDetailArray['caption'];
} else {
$caption = "";
}
if (isset($postDetailArray['publish'])) {
$publish = $postDetailArray['publish'];
} else {
$publish = TRUE;
}
if (isset($postDetailArray['postdate'])) {
$postdate = $postDetailArray['postdate'];
} else {
$postdate = "NOW()";
}
if (isset($postDetailArray['tagString'])) {
$tagString = $postDetailArray['tagString'];
} else {
$tagString = "";
}
You can use an array of defaults and then merge the argument array with the defaults. The defaults will be overridden if they appear in the argument array. A simple example:
$defaults = array(
'foo' => 'aaa',
'bar' => 'bbb',
'baz' => 'ccc',
);
$options = array(
'foo' => 'ddd',
);
$merged = array_merge($defaults, $options);
print_r($merged);
/*
Array
(
[foo] => ddd
[bar] => bbb
[baz] => ccc
)
*/
In your case, that would be:
function addLinkPost($postDetailArray) {
static $defaults = array(
'title' => 'Error: No Title',
'url' => 'no url',
'caption' => '',
'publish' => true,
'postdate' => 'NOW()',
'tagString' => '',
);
$merged = array_merge($defaults, $postDetailArray);
$title = $merged['title'];
$url = $merged['url'];
$caption = $merged['caption'];
$publish = $merged['publish'];
$postdate = $merged['postdate'];
$tagString = $merged['$tagString'];
}
You could do it like this:
function addLinkPost(array $postDetailArray)
{
$fields = array(
'key' => 'default value',
'title' => 'Error: No Title',
);
foreach ($fields as $key => $default) {
$$key = isset($postDetailArray[$key]) ? $postDetailArray[$key] : $default;
}
}
Simply edit the $fields array with your key and its default value.
Using the array as an argument is a good idea in this case. However, you could simplify the code in the function a bit by using the ternary operator (http://dk.php.net/ternary):
$title = isset($postDetailArray['title']) ? $postDetailArray['title'] : 'Error: No Title';
You could simplify it even more by doing the following:
function addLinkPost($data) {
$arguments = array('title', 'url', 'caption', 'publish', 'postdate', 'tagString');
foreach ($arguments as $value) {
$$value = isset($data[$value]) ? $data[$value] : 'Error: No '.$value;
}
}
Try this:
function addLinkPost($postDetailArray) {
foreach($array as $key=>$value){
$$key = (isset($value) && !empty($value)) ? $value : ('no '.$key);
}
//all keys are available as variables
var_dump($url); var_dump($publish); //etc
}
You could make all elements of the array parameters of the function. Check if the first is an array in the function and if so, extract the array.
function addLinkPost($title = null, $url = null, $caption = null, $publish = null, $postDate = null, $tagString = null)
{
if(is_array($title)) {
extract($title);
}
....
}
Maybe that makes the code a little more clear.
How about:
function getdefault($value, $default = null) {
return isset($value) ? $value : $default;
}
function addLinkPost($postDetailArray) {
$title = getdefault($postDetailArray['title'], 'Error: No Title');
$url = getdefault($postDetailArray['url'], 'no url');
$caption = getdefault($postDetailArray['caption'], '');
$publish = getdefault($postDetailArray['publish'], TRUE);
$postdate = getdefault($postDetailArray['postdate'], 'NOW()');
$tagString = getdefault($postDetailArray['tagString'], '');
}
or alternatively:
$defaults = array(
'title' => 'Error: No Title',
'url' => 'no url',
'caption' => '',
'publish' => TRUE,
'postdate' => 'NOW()',
'tagString' => '',
);
function addLinkPost($postDetailArray) {
global $defaults;
foreach ($defaults as $k => $v) {
$$k = isset($postDetailArray[$k]) ? $postDetailArray[$k] : $v;
}
}
With the one warning that if you have an array key of 'defaults' in $defaults, it will overwrite the global $defaults.