PHP Notes and Examples: Difference between revisions

From I Will Fear No Evil
Jump to navigation Jump to search
mNo edit summary
 
(11 intermediate revisions by the same user not shown)
Line 1: Line 1:
===PHP Notes and Examples===
===PHP Notes and Examples===
change Array to JSON
==change Array to JSON ==
<pre>
<pre>
$foo=json_encode($array,1);
$foo=json_encode($array,1);
Line 6: Line 6:
</pre>
</pre>


Convert a VALID JSON string to array
==Convert a VALID JSON string to array==
<pre>
<pre>
$foo=json_decode($json, True);
$foo=json_decode($json, True);
Line 12: Line 12:
</pre>
</pre>


Example foreach loop (simple)
==Example foreach loop (simple)==
<pre>
<pre>
foreach ($nestedArray1 as $Array1) {
foreach ($nestedArray1 as $Array1) {
Line 19: Line 19:
</pre>
</pre>


Example Try Catch block
==Example Try Catch block==
<pre>
<pre>
Use Exception;
Use Exception;
Line 33: Line 33:
</pre>
</pre>


Checking if file or dir exists.  Starting point:
==Checking if file or dir exists.  Starting point:==
<pre>
<pre>


Line 44: Line 44:
echo $path_parts['filename'], "\n";
echo $path_parts['filename'], "\n";
?>
?>
The above example will output:
/www/htdocs/inc
lib.inc.php
php
lib.inc
</pre>
==Go BACKWARDS in array==
From: [https://stackoverflow.com/questions/2194388/php-how-to-get-the-element-before-the-last-element-from-an-array php-how-to-get-the-element-before-the-last-element-from-an-array]
* Note that you need more than 2 elements in the array for this to work properly according to answer.
<pre>
<?php
$foo=["one","two","three","four"];
echo "TEST " . $foo[count($foo)-2];
?>
Returns TEST three
</pre>
All arrays have an "internal array pointer" which points to the current array element, PHP has several functions which allow you to navigate through the array and view the current elements key and value.
    end() - Set the internal pointer of an array to its last element
    reset() - Set the internal pointer of an array to its first element
    prev() - Rewind the internal array pointer
    next() - Advance the internal array pointer of an array
    current() - Return the current element in an array
    key() - Fetch a key from an array
    each() - Return the current key and value pair from an array and advance the array cursor
== Add Space before every capital letter==
From [https://bytes.com/topic/php/answers/8589-how-insert-space-before-capital-letters-string -how-insert-space-before-capital-letters-string]
<pre>
preg_replace('/(\w+)([A-Z])/U', '\\1 \\2', $cleanStorage);
</pre>
== Working with file creation and removal ==
<pre>
      $content = '<?php ' . $preProcessing . ' ?>';
      $file = dirname(__FILE__) . '/'. $event_name . '.php';
      file_put_contents($file, $content);
      include "$file";
      unlink "$file";
      $result['file'] = $file;
</pre>
</pre>


====Slim4 Framework Notes====
== Set defaults if not provided to function ==
[https://stackoverflow.com/questions/9166914/using-default-arguments-in-a-function| Using defaults in a function in PHP]
<pre>
function foo($blah, $x = null, $y = null) {
    if (null === $x) {
        $x = "some value";
    }
    if (null === $y) {
        $y = "some other value";
    }
    code here!
}
</pre>
 
== Make Indexed Array Unique ==
<pre>
$temp_array = array();
foreach ($array as &$v) {
    if (!isset($temp_array[$v['name']]))
        $temp_array[$v['name']] =& $v;
}
</pre>
 
== Array by reference ==
Using the & VARIABLE will change the value within the original array.  This was given by chatGPT questions.  Nice simple example
<pre>
// Without reference
$array1 = [1, 2, 3];
foreach ($array1 as $v) {
    $v = $v * 2;
}
print_r($array1);  // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 )
 
// With reference
$array2 = [1, 2, 3];
foreach ($array2 as &$v) {
    $v = $v * 2;
}
print_r($array2);  // Outputs: Array ( [0] => 2 [1] => 4 [2] => 6 )
</pre>
 
==Slim4 Framework Notes==
<pre>
<pre>
return $this->respondWithData($data);
return $this->respondWithData($data);
throw new HttpBadRequestException($this->request, "Error message details");
throw new HttpBadRequestException($this->request, "Error message details");
</pre>
</pre>
== Some cheat-sheets ==
Random cheat-sheets found on the net that are kinda useful
# [https://cheatography.com/davechild/cheat-sheets/php/| Looks like a pretty good PHP sheet]
# [https://cheatography.com/krabat1/cheat-sheets/php/| This one is REALLY big, but looks to have good info]
[[Category:PHP]]
[[Category:PHP]]

Latest revision as of 10:48, 20 September 2023

PHP Notes and Examples

change Array to JSON

$foo=json_encode($array,1);
echo $foo . "\n";

Convert a VALID JSON string to array

$foo=json_decode($json, True);
print_r($foo);

Example foreach loop (simple)

foreach ($nestedArray1 as $Array1) {
  do something with new array $array1[??};
}

Example Try Catch block

Use Exception;
try {
  someRandoFunction;
}
catch (Exception $e) {
  doSomethingWhenErrorFound;
}
catch (ErrorName $e) {
  cryToMamma;
}

Checking if file or dir exists. Starting point:


<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";
?>

The above example will output:

/www/htdocs/inc
lib.inc.php
php
lib.inc

Go BACKWARDS in array

From: php-how-to-get-the-element-before-the-last-element-from-an-array

  • Note that you need more than 2 elements in the array for this to work properly according to answer.
<?php
$foo=["one","two","three","four"];
echo "TEST " . $foo[count($foo)-2];
?>
Returns TEST three

All arrays have an "internal array pointer" which points to the current array element, PHP has several functions which allow you to navigate through the array and view the current elements key and value.

   end() - Set the internal pointer of an array to its last element
   reset() - Set the internal pointer of an array to its first element
   prev() - Rewind the internal array pointer
   next() - Advance the internal array pointer of an array
   current() - Return the current element in an array
   key() - Fetch a key from an array
   each() - Return the current key and value pair from an array and advance the array cursor

Add Space before every capital letter

From -how-insert-space-before-capital-letters-string

preg_replace('/(\w+)([A-Z])/U', '\\1 \\2', $cleanStorage); 

Working with file creation and removal

      $content = '<?php ' . $preProcessing . ' ?>';
      $file = dirname(__FILE__) . '/'. $event_name . '.php';
      file_put_contents($file, $content);
      include "$file";
      unlink "$file";
      $result['file'] = $file;

Set defaults if not provided to function

Using defaults in a function in PHP

function foo($blah, $x = null, $y = null) {
    if (null === $x) {
        $x = "some value";
    }
    if (null === $y) {
        $y = "some other value";
    }
    code here!
}

Make Indexed Array Unique

$temp_array = array();
foreach ($array as &$v) {
    if (!isset($temp_array[$v['name']]))
        $temp_array[$v['name']] =& $v;
}

Array by reference

Using the & VARIABLE will change the value within the original array. This was given by chatGPT questions. Nice simple example

// Without reference
$array1 = [1, 2, 3];
foreach ($array1 as $v) {
    $v = $v * 2;
}
print_r($array1);  // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 )

// With reference
$array2 = [1, 2, 3];
foreach ($array2 as &$v) {
    $v = $v * 2;
}
print_r($array2);  // Outputs: Array ( [0] => 2 [1] => 4 [2] => 6 )

Slim4 Framework Notes

return $this->respondWithData($data);
throw new HttpBadRequestException($this->request, "Error message details");

Some cheat-sheets

Random cheat-sheets found on the net that are kinda useful

  1. Looks like a pretty good PHP sheet
  2. This one is REALLY big, but looks to have good info