0

I want to edit values in a array php file.

this is lang.php    
$lang = array (
    'l_name' => "Language",
    'b' => "Break");

I want to replace 'l_name' => "Language", into 'l_name' => "Hi its me.",

how I can do it?

$fileContents = file_get_contents($path_to_file);
$search = array('l_name');
$replace = array('Hi, its me');
$newContents = str_replace($search, $replace, $fileContents);
$handle = fopen($path_to_file ,"w");
fwrite($handle, $newContents);
fclose($handle);

I tried this but its not working its replacing the key 'l_name'

I want to replace to value of key, How can i do it?

Thanks in advance.

1 Answer 1

1

Check below code and replace it accordingly.

<?php

//Replace 'l_name' key value:
echo "\n\nReplace 'l_name' key value: \n";
$lang = array (
    'l_name' => "Language",
    'b' => "Break");
$search = $lang['l_name'];
$replace = 'Hi, its me';
$newContents = str_replace($search, $replace, $lang);
print_r($newContents);

//Replace all key value
$newArr = array();
foreach($lang as $key=>$val)
{
  $newArr[$key] = 'Hi, its me';
}

echo "\n\nReplace all key value: \n";
print_r($newArr);

Output

Replace 'l_name' key value: 
Array
(
    [l_name] => Hi, its me
    [b] => Break
)


Replace all key value: 
Array
(
    [l_name] => Hi, its me
    [b] => Hi, its me
)

Demo: Click Here

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks bro its worked. But to replace all keys inside $lang ?
You have written that you need to replace only l_name value.
can't we use here $lang['l_name']; something? so that $lang can get all key ?
Give me your desire output. You need to replace for all keys with same replace value?
no, no, I need to replace all key with different values. Output Array ( [l_name] => Hi, its me [b] => Break [c] => another )
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.