How to replace an array with new array value in a file - php

I want to replace an array code inside my php file with new array dynamically
For e.g
<?php
$my_Array = array("key1" => "valu1");
?>
to
<?php
$my_Array = array("key2" => "valu2");
?>
Is that possible?

You can do this using url parameters like below.
Your url should be like mywebsite.com/test.php?key1=value1&key2=value2
In your php file
$myarray = array();
foreach ($_GET as $key => $value) {
$myarray[$key] = $value;
}
print_r($myarray);
Output should be like below
Array ( [key1] => value1 [key2] => value2 )

If it's saved in file and you need to replace it, use something like this:
<?php
$file = 'filename.php'; // path to the file
$data = file_get_contents($file);
$old = array("key1","valu1"); // old values to replace
$new = array("key2","valu2"); // the new values
$data = str_replace($old,$new,$data);
file_put_contents($file,$data);
?>
Is this what you need?

Related

Compare host name from array of URLs and get unique values

I need to compare URLs and remove duplicates from array but I want compare only host from url. I need skip http and https and www and others like last slash when I compare.
So when I have array:
$urls = array(
'http://www.google.com/test',
'https://www.google.com/test',
'https://www.google.com/example',
'https://www.facebook.com/example',
'http://www.facebook.com/example');
Result will be only
http://www.google.com/test
http://www.google.com/example
http://www.facebook.com/example
I tried to compare like :
$urls = array_udiff($urls, $urls, function ($a, $b) {
return strcmp(preg_replace('|^https?://(www\\.)?|', '', rtrim($a,'/')), preg_replace('|^https?://(www\\.)?|', '', rtrim($b,'/')));
});
But it return me empty array.
<?php
$urls = array(
'http://www.google.com/test',
'https://www.google.com/test',
'https://www.google.com/example',
'https://www.facebook.com/example',
'http://www.facebook.com/example');
$MyArray = [];
for($i=0;$i<count($urls);$i++) {
preg_match_all('/www.(.*)/', $urls[$i], $matches);
if (!in_array($matches[1], $MyArray))
$MyArray[] = $matches[1];
}
echo "<pre>";
print_r($MyArray);
echo "</pre>";
And the output is
Array
(
[0] => Array
(
[0] => google.com/test
)
[1] => Array
(
[0] => google.com/example
)
[2] => Array
(
[0] => facebook.com/example
)
)
trimmed and keeping only the host name
Try this approach :
<?php
function parseURLs(array $urls){
$rs = [];
foreach($urls as $url){
$segments = parse_url($url);
if(!in_array($segments['host'], $rs))
$rs[] = $segments['host'];
}
return $rs;
}
Then :
<?php
$urls = array(
'http://www.google.com',
'https://www.google.com',
'https://www.google.com/',
'https://www.facebook.com',
'http://www.facebook.com'
);
$uniqueURLs = parseURLs($urls);
print_r($uniqueURLs);
/* result :
Array
(
[0] => www.google.com
[1] => www.facebook.com
)
*/
You need to Loop through the URL's, Parse URL with PHP's url_parse() function and use array_unique to remove duplicates from array, so we are checking both the host and path ..
I have written a class for you:
<?php
/** Get Unique Values from array Values **/
Class Parser {
//Url Parser Function
public function arrayValuesUrlParser($urls) {
//Create Container
$parsed = [];
//Loop Through the Urls
foreach($urls as $url) {
$parse = parse_url($url);
$parsed[] = $parse["host"].$parse["path"];
//Delete Duplicates
$result = array_unique($parsed);
}
//Dump result
print_r($result);
}
}
?>
Using the Class
<?php
//Inlcude tghe Parser
include_once "Parser.php";
$urls = array(
'http://www.google.com/test',
'https://www.google.com/test',
'https://www.google.com/example',
'https://www.facebook.com/example',
'http://www.facebook.com/example');
//Instantiate
$parse = new Parser();
$parse->arrayValuesUrlParser($urls);
?>
You can do it in one file if you don't need to seperate files but you will have to remove include_once if you are using one php file. This class is also on PHP Classes, did it for fun !
Best of Luck !

Want to Filter an array according to value

I have a variable $a='san-serif' and an array Font_list[] now I want only the arrays whose category is 'san-serif' will be filtered. I tried a lot of codes nothing seems working here is my code:-
public function filterFont() {
$a = $_POST['key'];
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=''";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
$filter = filter($font_list);
print_r(array_filter($font_list, $filter));
}
Please help me :-(
What i understood according to that you want something like below:-
<?php
$a='san-serif'; // category you want to search
$font_list=Array('0'=>Array('font_name' => "sans-sherif",'category' => "san-serif"),'1'=>Array('font_name' => "times-new-roman",'category' => "san-serif"),'2'=>Array('font_name' => "sans-sherif",'category' => "roman"));
// your original array seems something like above i mentioned
echo "<pre/>";print_r($font_list); // print original array
$filtered_data = array(); // create new array
foreach($font_list as $key=>$value){ // iterate through original array
if($value['category'] == $a){ // if array category name is equal to serach category name
$filtered_data[$key] = $value; // assign that array to newly created array
}
}
echo "<pre/>";print_r($filtered_data); // print out new array
Output:- https://eval.in/597605

PHP Config.ini file parsing with multi-level arrays

I have a config.ini file that has a number of these types of variables:
site.social.twitter = "URL"
site.social.facebook = "URL"
site.social.google-plus = "URL"
I use PHP's built-in function to parse the INI.
$config = parse_ini_file(__DIR__ ."/../config.ini");
The next step is to get this (site.social.twitter)
to become an array.
$config['site']['social']['twitter']
You could just 'explode()', but it doesn't quite get there. Is there any simpler solutions to something like this?
OK, so you can look at using sections and the array syntax for INI files such as:
[site]
social[twitter] = URL
social[facebook] = URL
social[google-plus] = URL
Then pass true as the second argument:
$config = parse_ini_file(__DIR__ ."/../config.ini", true);
Or to build using your existing INI structure (adapted from How to access and manipulate multi-dimensional array by key names / path?):
$array = array();
foreach($config as $path => $value) {
$temp = &$array;
foreach(explode('.', $path) as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
$config = $array;
print_r($config);
Does simply referencing $config['site']['social'] get you the array you want? According to the documentation this should yield:
Array
(
[twitter] => "URL"
[facebook] => "URL"
[google-plus] => "URL"
)

How to store each array value in a variable with PHP

I have an array that looks something like this:
Array
(
[2] => http://www.marleenvanlook.be/admin.php
[4] => http://www.marleenvanlook.be/checklogin.php
[5] => http://www.marleenvanlook.be/checkupload.php
[6] => http://www.marleenvanlook.be/contact.php
)
What I want to do is store each value from this array to a variable (using PHP). So for example:
$something1 = "http://www.marleenvanlook.be/admin.php";
$something2 = "http://www.marleenvanlook.be/checklogin.php";
...
You can use extract():
$data = array(
'something1',
'something2',
'something3',
);
extract($data, EXTR_PREFIX_ALL, 'var');
echo $var0; //Output something1
More info on http://br2.php.net/manual/en/function.extract.php
Well.. you could do something like this?
$myArray = array("http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
$i = 0;
foreach($myArray as $value){
${'something'.$i} = $value;
$i++;
}
echo $something0; //http://www.marleenvanlook.be/admin.php
This would dynamically create variables with names like $something0, $something1, etc holding a value of the array assigned in the foreach.
If you want the keys to be involved you can also do this:
$myArray = array(1 => "http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
foreach($myArray as $key => $value){
${'something'.$key} = $value;
}
echo $something1; //http://www.marleenvanlook.be/admin.php
PHP has something called variable variables which lets you name a variable with the value of another variable.
$something = array(
'http://www.marleenvanlook.be/admin.php',
'http://www.marleenvanlook.be/checklogin.php',
'http://www.marleenvanlook.be/checkupload.php',
'http://www.marleenvanlook.be/contact.php',
);
foreach($something as $key => $value) {
$key = 'something' . $key;
$$key = $value;
// OR (condensed version)
// ${"something{$key}"} = $value;
}
echo $something2;
// http://www.marleenvanlook.be/checkupload.php
But the question is why would you want to do this? Arrays are meant to be accessed by keys, so you can just do:
echo $something[2];
// http://www.marleenvanlook.be/checkupload.php
What I would do is:
$something1 = $the_array[2];
$something2 = $the_array[4];

Adding elements to an array using key/value in PHP?

I know I can add elemnts to an array like this:
$arr = array("foo" => "bar", 12 => true);
Now, how can I do that in a foreach using dynamic values? I have this code:
foreach ($values as $value) {
$imagePath = $value->getImagePath();
$dependsOn = $value->getDependsOn();
$dependsOn = explode(':', $dependsOn);
$dependsOnOptionValueTitle = trim($dependsOn[1]);
array_push($paths, $dependsOnOptionValueTitle => $imagePath); // not working
}
How can I add key/value pairs to my $paths array?
Instead of
array_push($paths, $dependsOnOptionValueTitle => $imagePath); // not working
you should be able to use
$paths[$dependsOnOptionValueTitle] = $imagePath;
From what I can see, this is what you're trying to do:
$paths[$dependsOnOptionValueTitle] = $imagePath;
Comment if I'm wrong and I'll try to fix it.

Categories