Skip to content

Instantly share code, notes, and snippets.

@bablukpik
Last active March 20, 2019 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bablukpik/860f3369f0e43d71bd16def20cf82daf to your computer and use it in GitHub Desktop.
Save bablukpik/860f3369f0e43d71bd16def20cf82daf to your computer and use it in GitHub Desktop.
-> A multidimensional array is an array containing one or more arrays. A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).
//Array Functions:
array_pop() ->pops an element off end of the array.
array_push() ->pushes an element into the end of the array.
array_shift() ->pops an element off the beginning of the array.
array_unshift() ->pushes an element into the beginning of the array.
array_key_exists($key, $array2)
array_diff(array1,array2,array3...);
array_intersect($array1, $array2);
array_search("red",$a);
in_array("Glenn", $people)
implode("", $value)
explode(" ",$str)
str_split("Hello")
substr("Hello world",10)
substr("Hello world",-10)
end(explode('_', $string))
array_pop(explode('_', $string));
strrpos()
split()
array_values()
array_map('array_values', $arr)
array_multisort($result, SORT_ASC)
next($array);
reset($array);
current($array)
prev()
list();
key($properties);
array_keys($result['node'])
array_splice($array, $i, 1)
array_merge($array)
array_unset($unsets, $array);
unset($arr1);
array_replace()
array_replace_recursive()
//In a foreach loop, $value means array's or object's values or items or item group if multidimensional array and $key means array or object name or fieldHead or fieldName or number index
//Removing new lines or line breaks from string
->Single new line removes
$titles = preg_replace("/\s/",'',$titles);
-> Double new lines removing
trim(preg_replace('/\s\s+/', ' ', $string));
Or
preg_replace( "/\r|\n/", "", $yourString );
Or
$string = str_replace(array("\r", "\n"), '', $string);
$string = str_replace("\n", "", $string);
$string = str_replace("\r", "", $string);
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
glob("/path/to/folder/*.txt")
N.B,
->Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line
->A line feed means moving one line forward. The code is \n. A carriage return means moving the cursor to the beginning of the line. The code is \r.
->Consider Carriage Return CR and New Line NL are different from
->Often abbreviated CR, a carriage return is a special code that moves the cursor (or print head) to the beginning of the current line.
//Difference between $arr[1] and $arr[1][1] in two dimensional array
$arr[1] is an array (an element) of $arr and $arr[1][1] is an element of the $array
//
is_numeric($v)
unset($array1[$key]);
// Field name and Cell value from different array
$donkiTitle = isset($_SESSION['donkiTitle'])?$_SESSION['donkiTitle']:array();
$clientMakerMapData = isset($_SESSION['clientMakerMapData'])?$_SESSION['clientMakerMapData']:array();
// Get server data
//$serverData = $_SESSION['serverData'];
//$titles = reset($serverData);
$exportData = array();
foreach ($clientMakerMapData as $k => $row) {
$rowData = array();
foreach ($donkiTitle as $title) {
$rowData[$title] = isset($row[$title]) ? $row[$title] : '';
}
$exportData[] = $rowData;
}
//An element remove and reindex
unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array
Or
// Make sure to reset the array's current index
reset($array);
$key = key($array);
unset($array[$key]);
//preg_match for check valid data
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
//filter_var()
//Array Loops:
//v.01
<?php
function diverse_array($vector) {
$result = array();
foreach($vector as $key1 => $value1)
foreach($value1 as $key2 => $value2)
$result[$key2][$key1] = $value2;
return $result;
}
?>
//v.02
foreach($aHash as $key=>$val) $tmp[] = $aHash[$key];
//v.02
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) $tmp[] = $aHash[$key[$i]];
//v.03
array_keys() / array_values()
//v.04
foreach($aHash as $key=>$val) $aHash[$key] .= "a";
//v.05
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) $aHash[$key[$i]] .= "a";
//v.06
if(is_array($sub_name)){
foreach(array_keys($sub_name) as $key){
$files[$name][$key] = array(
'name' => $file['name'][$key],
'type' => $file['type'][$key],
'tmp_name' => $file['tmp_name'][$key],
'error' => $file['error'][$key],
'size' => $file['size'][$key],
);
$files[$name] = multiple($files[$name], FALSE);
}
}
//How to make variable form an indexed array
$arr_con = array_combine($arr,$arr);
die(var_dump($arr_con));
extract($arr_con);
echo $id;
//v.02
$arr = array('id','name');
$str = implode(',', $arr);
echo $str;
//How to make variable from an associative array
$arr_data = array_map(function($k, $v){
return "$k='$v'";
}, array_keys($data), array_values($data));
$data_str = implode(", ",$arr_data);
//To echo after processing between array and custom parameter with array_walk
//ROLL_NO LIKE '" . $requestData['search']['value'] . "%'
$presentable_cols = array('id'=>'id','name'=>'name','program'=>'program');
$a=array("a"=>"red","b"=>"green","c"=>"blue");
$i=0;
function myfunction($value,$key,$presentable_cols)
{
echo " $key LIKE '%" . 'request_data' . "%' OR";
}
array_walk($a,"myfunction",$presentable_cols);
//v.02
// search data from table
function search_data($value,$key,$presentable_cols)
{
echo "$key LIKE '" . $_REQUEST['search']['value'] . "%'";
}
$query = $this->db->query("
SELECT $presentable_cols_str
FROM $table
WHERE ".array_walk($presentable_cols,"search_data")."
ORDER BY " . $sortable_cols[$requestData['order'][0]['column']] . " " . $requestData['order'][0]['dir'] . " LIMIT " . $requestData['start'] . " ," . $requestData['length']
)->result();
//Array_walk alternative
$request_data = "Bablu";
$presentable_cols = array('id'=>'13141203051','name'=>'Bablu Ahmed','program'=>'B.Sc. in CSE', 'country'=>'Bangladesh');
$find_str_arr=[];
foreach ($presentable_cols as $key => $value)
{
$find_str_arr[] = "$key LIKE '%$request_data%'";
}
$find_sql_str = implode(' OR ', $find_str_arr);
echo $find_sql_str;
// Number of Duplicate Value Count in an array like sql "SUM OVER PARTITION BY" --------------------------------------------
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
For example:
$newarr = [];
foreach ($dbAdmin as $key=>$value)
{
$newarr[] = $value->DIVISIONID;
}
$counts_division_id = array_count_values($newarr);
<?php foreach ($dbAdmin as $key => $row) { ?>
<tr>
<?php
//$total = $row->totalDis;
$total = $counts_division_id[$row->DIVISIONID];
if ($count != 0)
$count--;
else
{
echo "<td rowspan=" . ($total + 1) . ">" . $row->Division . "</td>";
$count = $total - 1;
}
?>
<td><?php echo $row->District; ?></td>
<td><?php echo $row->HLT; ?></td>
......
<tr>
<?php } ?>
//How to expand from one array of arrays into two arrays of arrays in PHP-------------------------
$arr_normal = [];
$arr_modc = [];
foreach ($borneSenction as $key => $row)
{
if($row->BRANCH_ID != 16)
{
array_push($arr_normal, $row);
}
else
{
array_push($arr_modc, $row);
}
}
//Dynamic Array and its fixed element (rowspan increment by 1) ---------------------------------
$arr = array();
if(empty($arr[$row->Branch])){
$arr[$row->Branch]['rowspan'] = 1;
$arr[$row->Branch]['printed'] = 'no';
}else{
$arr[$row->Branch]['rowspan'] += 1;
}
Here, arr[$row->Branch] is dynamic array
And its two elements are -
$arr[$row->Branch]['rowspan'] = 1;
$arr[$row->Branch]['printed'] = 'no';
//Multidimensional Array
$array = array(
0 => array(
'name' => 'John Doe',
'email' => 'john@example.com'
),
1 => array(
'name' => 'Jane Doe',
'email' => 'jane@example.com'
),
);
Which is equivalent to:
$array = array();
//$array[0] = array();
$array[0]['name'] = 'John Doe';
$array[0]['email'] = 'john@example.com';
//$array[1] = array();
$array[1]['name'] = 'Jane Doe';
$array[1]['email'] = 'jane@example.com';
For Example:
// zone and area name
$arr_zone_area = [];
$i = 0;
foreach ($area as $key_area=>$row_area)
{
foreach ($nominalRoll as $key => $value) {
if ($row_area->ADMIN_ID == $value->AREA_ID)
{
$arr_zone_area[$key_area][0] = $row_area->ZONE_NAME;
$arr_zone_area[$key_area][1] = $row_area->AREA_NAME;
}
}
echo ++$i;
}
die(print_r($arr_zone_area));
Output:
(
[0] => Array
(
[0] => Dhaka
[1] => Admin Dhaka
)
)
For Object Properties...
foreach ($area as $key_area=>$row_area)
{
foreach ($nominalRoll as $key => $value)
{
if ($row_area->ADMIN_ID == $value->AREA_ID)
{
/*$arr_zone_area[$key_area]['ZONE_NAME'] = $row_area->ZONE_NAME;
$arr_zone_area[$key_area]['AREA_NAME'] = $row_area->AREA_NAME;
$arr_zone_area[$key_area]['ADMIN_ID'] = $row_area->ADMIN_ID;*/
$arr_zone_area[$key_area] = (object)[
'ZONE_NAME' => $row_area->ZONE_NAME,
'AREA_NAME' => $row_area->AREA_NAME,
'ADMIN_ID' => $row_area->ADMIN_ID,
];
}
}
}
//Pass By Reference
$myvar = '';
functionName(someArgument, function() use( &$myvar) {
$variable = "something";
});
echo $myvar;
Note that you are be able to modify $myvar and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using &
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment