PHP Notes and Examples

From I Will Fear No Evil
Revision as of 16:21, 19 June 2023 by Chubbard (talk | contribs)
Jump to navigation Jump to search

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


Slim4 Framework Notes

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