i am trying to create some switches saved in other files, already tried to make it turn a text file into array but it didnt worked well since itdoesnt seem to even read the file properly and dont get anything from inside of it. now i got the idea of having php files that have the arrays and it can be changed by a main php file
this will be the entire switch file:
<?php
function getarray(){
$a = array(
'name_on' => 0,
'picture_on' = 0,
'custom_styling_on' = 0
);
return $a;
}
?>
and i would like to edit the values of the array from the main file, but i dont know exactly how.
but if someone know how to create an array from a text file it will work, but just remember i tried what the answer of other questions said to and didnt worked
as ADyson said
a json for an array will be way more useful, i have changed my code to,so if i press a button it will change the value:
<?php
function getvalues(){
$json = file_get_contents(__DIR__."\switch.json");
$arr = json_decode($json,true);
return $arr;
}
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['btn']))
{
setval('name',0);
}
function setval($key,$value){
$json = file_get_contents(__DIR__."\switch.json");
$arr = json_decode($json,true);
$arr[$key] = $value;
$jarr = json_encode($arr);
file_put_contents("switch.json",$jarr);
}
?>
Suppose I write a line
include Yii::app()->basepath.'/views/email/email_friend.php';
now how can i take the response of this line into a variable?
like
$abc = include Yii::app()->basepath.'/views/email/email_friend.php';
Have a look at the PHP docs for include http://php.net/manual/en/function.include.php
Example #5 is I think what you're looking for
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
All you have to do is the included file had a return with the desired value. It's been quite popular for some time.
so the include.php should like the following:
<?php
return ' World!';
and the including one:
<?php
$a = include('include.php');
echo 'Hello'.$a; // Hello World!
When you include it's like you're copy/pasting the code into your PHP. If it's just inline PHP and there was a variable $abc in the include file 'email_friend.php' then you could access the variable normally after the include.
I know this is an old post. I hope my answer will be useful to someone. I combined the Accepted answer with the answer "PHP/7 you can use a self-invoking anonymous function..."
define( 'WPPATH', dirname(dirname(__FILE__)) . '/public/partials/bla-bla.php' );
$publicDisplayContent = (function () {
// [PHP/7 you can use a self-invoking anonymous function](https://stackoverflow.com/a/41568962/601770)
// https://stackoverflow.com/a/5948404/601770
ob_start();
require_once(WPPATH);
return ob_get_clean();
})(); // PHP/7 you can use a self-invoking anonymous function
error_log( 'activate() >> $publicDisplayContent: ' . print_r( $publicDisplayContent, true ) );
DOT DOT DOT
'post_content' => $publicDisplayContent,
Is there a Shortcut for
echo "<pre>";
print_r($myarray);
echo "</pre>";
It is really annoying typing those just to get a readable format of an array.
This is the shortest:
echo '<pre>',print_r($arr,1),'</pre>';
The closing tag can also be omitted.
Nope, you'd just have to create your own function:
function printr($data) {
echo "<pre>";
print_r($data);
echo "</pre>";
}
Apparantly, in 2018, people are still coming back to this question. The above would not be my current answer. I'd say: teach your editor to do it for you. I have a whole bunch of debug shortcuts, but my most used is vardd which expands to: var_dump(__FILE__ . ':' . __LINE__, $VAR$);die();
You can configure this in PHPStorm as a live template.
You can set the second parameter of print_r to true to get the output returned rather than directly printed:
$output = print_r($myarray, true);
You can use this to fit everything into one echo (don’t forget htmlspecialchars if you want to print it into HTML):
echo "<pre>", htmlspecialchars(print_r($myarray, true)), "</pre>";
If you then put this into a custom function, it is just as easy as using print_r:
function printr($a) {
echo "<pre>", htmlspecialchars(print_r($a, true)), "</pre>";
}
Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set
header('Content-type: text/plain');
echo '<pre>' . print_r( $myarray, true ) . '</pre>';
From the PHP.net print_r() docs:
When [the second] parameter is set to TRUE, print_r() will return the information rather than print it.
teach your editor to do it-
after writing "pr_" tab i get exactly
print("<pre>");
print_r($);
print("</pre>");
with the cursor just after the $
i did it on textmate by adding this snippet:
print("<pre>");
print_r(\$${1:});
print("</pre>");
If you use VS CODE, you can use :
Ctrl + Shift + P -> Configure User Snippets -> PHP -> Enter
After that you can input code to file php.json :
"Show variable user want to see": {
"prefix": "pre_",
"body": [
"echo '<pre>';",
"print_r($variable);",
"echo '</pre>';"
],
"description": "Show variable user want to see"
}
After that you save file php.json, then you return to the first file with any extension .php and input pre_ -> Enter
Done, I hope it helps.
If you are using XDebug simply use
var_dump($variable);
This will dump the variable like print_r does - but nicely formatted and in a <pre>.
(If you don't use XDebug then var_dump will be as badly formated as print_r without <pre>.)
echo "<pre/>"; print_r($array);
Both old and accepted, however, I'll just leave this here:
function dump(){
echo (php_sapi_name() !== 'cli') ? '<pre>' : '';
foreach(func_get_args() as $arg){
echo preg_replace('#\n{2,}#', "\n", print_r($arg, true));
}
echo (php_sapi_name() !== 'cli') ? '</pre>' : '';
}
Takes an arbitrary number of arguments, and wraps each in <pre> for CGI requests. In CLI requests it skips the <pre> tag generation for clean output.
dump(array('foo'), array('bar', 'zip'));
/*
CGI request CLI request
<pre> Array
Array (
( [0] => foo
[0] => foo )
) Array
</pre> (
<pre> [0] => bar
Array [1] => zip
( )
[0] => bar
[0] => zip
)
</pre>
I just add function pr() to the global scope of my project.
For example, you can define the following function to global.inc (if you have) which will be included into your index.php of your site. Or you can directly define this function at the top of index.php of root directory.
function pr($obj)
{
echo "<pre>";
print_r ($obj);
echo "</pre>";
}
Just write
print_r($myarray); //it will display you content of an array $myarray
exit(); //it will not execute further codes after displaying your array
Maybe you can build a function / static class Method that does exactly that. I use Kohana which has a nice function called:
Kohana::Debug
That will do what you want. That's reduces it to only one line. A simple function will look like
function debug($input) {
echo "<pre>";
print_r($input);
echo "</pre>";
}
function printr($data)
{
echo "<pre>";
print_r($data);
echo "</pre>";
}
And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php
include('functions.php');
printr($data);
I would go for closing the php tag and then output the <pre></pre> as html, so PHP doesn't have to process it before echoing it:
?>
<pre><?=print_r($arr,1)?></pre>
<?php
That should also be faster (not notable for this short piece) in general. Using can be used as shortcode for PHP code.
<?php
$people = array(
"maurice"=> array("name"=>"Andrew",
"age"=>40,
"gender"=>"male"),
"muteti" => array("name"=>"Francisca",
"age"=>30,
"gender"=>"Female")
);
'<pre>'.
print_r($people).
'</pre>';
/*foreach ($people as $key => $value) {
echo "<h2><strong>$key</strong></h2><br>";
foreach ($value as $values) {
echo $values."<br>";;
}
}*/
//echo $people['maurice']['name'];
?>
I generally like to create my own function as has been stated above. However I like to add a few things to it so that if I accidentally leave in debugging code I can quickly find it in the code base. Maybe this will help someone else out.
function _pr($d) {
echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
echo "</div>";
echo '<pre>';
if(is_array($d)) {
print_r($d);
} else if(is_object($d)) {
var_dump($d);
}
echo '</pre>';
}
You can create Shortcut key in Sublime Text Editor using Preferences -> Key Bindings
Now add below code on right-side of Key Bindings within square bracket []
{
"keys": ["ctrl+shift+c"],
"command": "insert_snippet",
"args": { "contents": "echo \"<pre>\";\nprint_r(${0:\\$variable_to_debug});\necho \"</pre>\";\ndie();\n" }
}
Enjoy your ctrl+shift+c shortcut as a Pretty Print of PHP.
Download AutoHotKey program from the official website: [https://www.autohotkey.com/]
After Installation process, right click in any folder and you will get as the following image: https://i.stack.imgur.com/n2Rwz.png
Select AutoHotKey Script file, open it with notePad or any text editor Write the following in the file:
::Your_Shortcut::echo '<pre>';var_dump();echo '</pre>';exit();
the first ::Your_Shortcut means the shortcut you want, I choose for example vard.
Save the file.
Double-click on the file to run it, after that your shortcut is ready.
You can test it by write your shortcut and click space.
For more simpler way
echo ""; print_r($test); exit();
I want to call require_once("test.php") but not display result and save it into variable like this:
$test = require_once('test.php');
//some operations like $test = preg_replace(…);
echo $test;
Solution:
test.php
<?php
$var = '/img/hello.jpg';
$res = <<<test
<style type="text/css">
body{background:url($var)#fff !important;}
</style>
test;
return $res;
?>
main.php
<?php
$test = require_once('test.php');
echo $test;
?>
Is it possible?
Yes, but you need to do an explicit return in the required file:
//test.php
<? $result = "Hello, world!";
return $result;
?>
//index.php
$test = require_once('test.php'); // Will contain "Hello, world!"
This is rarely useful - check Konrad's output buffer based answer, or adam's file_get_contents one - they are probably better suited to what you want.
“The result” presumably is a string output?
In that case you can use ob_start to buffer said output:
ob_start();
require_once('test.php');
$test = ob_get_contents();
EDIT From the edited question it looks rather like you want to have a function inside the included file. In any case, this would probably be the (much!) cleaner solution:
<?php // test.php:
function some_function() {
// Do something.
return 'some result';
}
?>
<?php // Main file:
require_once('test.php');
$result = test_function(); // Calls the function defined in test.php.
…
?>
file_get_contents will get the content of the file. If it's on the same server and referenced by path (rather than url), this will get the content of test.php. If it's remote or referenced by url, it will get the output of the script.
How can I put the result of an include into a PHP variable?
I tried file_get_contents but it gave me the actual PHP code, whereas I want whats echoed.
Either capture anything that's printed in the include file through output buffering
ob_start();
include 'yourFile.php';
$out = ob_get_contents();
ob_end_clean();
or alternatively, set a return value in the script, e.g.
// included script
return 'foo';
// somewhere else
$foo = include 'yourFile.php';
See Example 5 of http://de2.php.net/manual/en/function.include.php
or simply return a value from an included file as explained here.
return.php:
<?php
$var = 'PHP';
return $var;
?>
$foo = include 'return.php';
echo $foo; // prints 'PHP'