0
# PHP Functions
1
2
Comprehensive PHP standard library functions ported to JavaScript. This module contains 321 functions across 20 categories, covering virtually all commonly used PHP functionality.
3
4
## Capabilities
5
6
### Array Functions (73 functions)
7
8
Array manipulation and processing functions for creating, modifying, and analyzing arrays.
9
10
```javascript { .api }
11
/**
12
* Array manipulation functions
13
*/
14
php.array.array_change_key_case(array, case) // Change key case
15
php.array.array_chunk(input, size, preserve_keys) // Split into chunks
16
php.array.array_column(array, column_key, index_key) // Extract column
17
php.array.array_combine(keys, values) // Combine arrays
18
php.array.array_count_values(array) // Count values
19
php.array.array_diff(array1, array2, ...) // Array difference
20
php.array.array_diff_assoc(array1, array2, ...) // Diff with keys
21
php.array.array_fill(start_index, num, value) // Fill with value
22
php.array.array_filter(array, callback, flag) // Filter elements
23
php.array.array_flip(array) // Flip keys/values
24
php.array.array_intersect(array1, array2, ...) // Array intersection
25
php.array.array_keys(array, search_value, strict) // Get all keys
26
php.array.array_map(callback, array1, ...) // Map callback
27
php.array.array_merge(array1, array2, ...) // Merge arrays
28
php.array.array_pad(array, size, value) // Pad to length
29
php.array.array_pop(array) // Remove last element
30
php.array.array_push(array, element1, ...) // Add elements to end
31
php.array.array_reverse(array, preserve_keys) // Reverse array
32
php.array.array_search(needle, haystack, strict) // Search for value
33
php.array.array_slice(array, offset, length, preserve_keys) // Extract slice
34
php.array.array_sum(array) // Sum values
35
php.array.array_unique(array, sort_flags) // Remove duplicates
36
php.array.array_values(array) // Get all values
37
php.array.count(mixed_var, mode) // Count elements
38
php.array.in_array(needle, haystack, strict) // Check value exists
39
php.array.range(start, end, step) // Create range
40
php.array.sort(array, sort_flags) // Sort array
41
```
42
43
**Usage Examples:**
44
45
```javascript
46
const locutus = require('locutus');
47
48
// Array merging
49
const merged = locutus.php.array.array_merge([1, 2], [3, 4]); // [1, 2, 3, 4]
50
51
// Array filtering
52
const numbers = [1, 2, 3, 4, 5];
53
const even = locutus.php.array.array_filter(numbers, (n) => n % 2 === 0); // [2, 4]
54
55
// Array chunking
56
const chunked = locutus.php.array.array_chunk([1, 2, 3, 4, 5, 6], 2); // [[1, 2], [3, 4], [5, 6]]
57
```
58
59
### String Functions (91 functions)
60
61
Comprehensive string manipulation and processing functions.
62
63
```javascript { .api }
64
/**
65
* String manipulation functions
66
*/
67
php.strings.addslashes(str) // Add slashes
68
php.strings.chr(ascii) // ASCII to char
69
php.strings.explode(delimiter, string, limit) // Split string
70
php.strings.html_entity_decode(string, quote_style, charset) // Decode HTML
71
php.strings.htmlentities(string, quote_style, charset, double_encode) // Encode HTML
72
php.strings.htmlspecialchars(string, quote_style, charset, double_encode) // Encode special chars
73
php.strings.implode(glue, pieces) // Join array
74
php.strings.ltrim(str, charlist) // Left trim
75
php.strings.md5(str) // MD5 hash
76
php.strings.nl2br(str, is_xhtml) // Newlines to BR
77
php.strings.ord(string) // Char to ASCII
78
php.strings.rtrim(str, charlist) // Right trim
79
php.strings.sha1(str) // SHA1 hash
80
php.strings.sprintf(format, ...args) // Format string
81
php.strings.str_pad(input, pad_length, pad_string, pad_type) // Pad string
82
php.strings.str_repeat(input, multiplier) // Repeat string
83
php.strings.str_replace(search, replace, subject, count) // Replace text
84
php.strings.strlen(string) // String length
85
php.strings.strpos(haystack, needle, offset) // Find position
86
php.strings.strtolower(str) // To lowercase
87
php.strings.strtoupper(str) // To uppercase
88
php.strings.substr(str, start, length) // Substring
89
php.strings.trim(str, charlist) // Trim whitespace
90
php.strings.ucfirst(str) // Uppercase first
91
php.strings.ucwords(str, delimiters) // Uppercase words
92
```
93
94
**Usage Examples:**
95
96
```javascript
97
const locutus = require('locutus');
98
99
// String manipulation
100
const length = locutus.php.strings.strlen('Hello World'); // 11
101
const upper = locutus.php.strings.strtoupper('hello'); // 'HELLO'
102
const padded = locutus.php.strings.str_pad('test', 10, '0', 'STR_PAD_LEFT'); // '000000test'
103
104
// String formatting
105
const formatted = locutus.php.strings.sprintf('Hello %s, you are %d years old', 'John', 25);
106
// 'Hello John, you are 25 years old'
107
```
108
109
### Math Functions (46 functions)
110
111
Mathematical operations and functions.
112
113
```javascript { .api }
114
/**
115
* Mathematical functions
116
*/
117
php.math.abs(mixed_number) // Absolute value
118
php.math.acos(arg) // Arc cosine
119
php.math.asin(arg) // Arc sine
120
php.math.atan(arg) // Arc tangent
121
php.math.atan2(y, x) // Arc tangent of y/x
122
php.math.ceil(value) // Round up
123
php.math.cos(arg) // Cosine
124
php.math.deg2rad(number) // Degrees to radians
125
php.math.exp(arg) // e^x
126
php.math.floor(value) // Round down
127
php.math.log(arg, base) // Logarithm
128
php.math.max(...values) // Maximum value
129
php.math.min(...values) // Minimum value
130
php.math.pow(base, exp) // Power
131
php.math.rand(min, max) // Random number
132
php.math.round(val, precision, mode) // Round number
133
php.math.sin(arg) // Sine
134
php.math.sqrt(arg) // Square root
135
php.math.tan(arg) // Tangent
136
```
137
138
### DateTime Functions (15 functions)
139
140
Date and time manipulation functions.
141
142
```javascript { .api }
143
/**
144
* Date and time functions
145
*/
146
php.datetime.date(format, timestamp) // Format date
147
php.datetime.getdate(timestamp) // Get date info
148
php.datetime.gmdate(format, timestamp) // GMT date
149
php.datetime.mktime(hour, minute, second, month, day, year) // Make timestamp
150
php.datetime.strftime(format, timestamp) // Format with locale
151
php.datetime.strtotime(time, now) // Parse datetime
152
php.datetime.time() // Current timestamp
153
```
154
155
### Variable Functions (30 functions)
156
157
Variable type checking and manipulation functions.
158
159
```javascript { .api }
160
/**
161
* Variable functions
162
*/
163
php.var.is_array(variable) // Check if array
164
php.var.is_bool(variable) // Check if boolean
165
php.var.is_float(variable) // Check if float
166
php.var.is_int(variable) // Check if integer
167
php.var.is_null(variable) // Check if null
168
php.var.is_numeric(variable) // Check if numeric
169
php.var.is_object(variable) // Check if object
170
php.var.is_string(variable) // Check if string
171
php.var.isset(variable) // Check if set
172
php.var.empty(variable) // Check if empty
173
php.var.gettype(variable) // Get variable type
174
php.var.serialize(variable) // Serialize variable
175
php.var.unserialize(str) // Unserialize string
176
```
177
178
### Other PHP Categories
179
180
#### BC Math Functions (7 functions)
181
```javascript { .api }
182
php.bc.bcadd(left_operand, right_operand, scale) // Add
183
php.bc.bccomp(left_operand, right_operand, scale) // Compare
184
php.bc.bcdiv(left_operand, right_operand, scale) // Divide
185
php.bc.bcmul(left_operand, right_operand, scale) // Multiply
186
php.bc.bcround(number, precision) // Round
187
php.bc.bcscale(scale) // Set scale
188
php.bc.bcsub(left_operand, right_operand, scale) // Subtract
189
```
190
191
#### Character Type Functions (11 functions)
192
```javascript { .api }
193
php.ctype.ctype_alnum(text) // Alphanumeric check
194
php.ctype.ctype_alpha(text) // Alphabetic check
195
php.ctype.ctype_digit(text) // Digit check
196
php.ctype.ctype_lower(text) // Lowercase check
197
php.ctype.ctype_upper(text) // Uppercase check
198
```
199
200
#### Filesystem Functions (6 functions)
201
```javascript { .api }
202
php.filesystem.basename(path, suffix) // Get basename
203
php.filesystem.dirname(path) // Get directory name
204
php.filesystem.file_exists(filename) // Check file exists
205
php.filesystem.pathinfo(path, options) // Get path info
206
```
207
208
#### JSON Functions (3 functions)
209
```javascript { .api }
210
php.json.json_decode(json_string, assoc, depth, options) // Decode JSON
211
php.json.json_encode(value, options, depth) // Encode JSON
212
php.json.json_last_error() // Get last error
213
```
214
215
#### Network Functions (6 functions)
216
```javascript { .api }
217
php.network.ip2long(ip_address) // IP to long
218
php.network.long2ip(proper_address) // Long to IP
219
php.network.inet_ntop(in_addr) // Binary to presentation
220
php.network.inet_pton(ip_address) // Presentation to binary
221
```
222
223
#### URL Functions (8 functions)
224
```javascript { .api }
225
php.url.base64_encode(data) // Base64 encode
226
php.url.base64_decode(data) // Base64 decode
227
php.url.parse_url(str, component) // Parse URL
228
php.url.urlencode(str) // URL encode
229
php.url.urldecode(str) // URL decode
230
php.url.rawurlencode(str) // Raw URL encode
231
php.url.rawurldecode(str) // Raw URL decode
232
```
233
234
#### Execution Functions (1 function)
235
```javascript { .api }
236
php.exec.escapeshellarg(arg) // Escape shell arguments
237
```
238
239
#### Function Handling Functions (5 functions)
240
```javascript { .api }
241
php.funchand.call_user_func(cb, ...parameters) // Call user function
242
php.funchand.call_user_func_array(cb, parameters) // Call function with array
243
php.funchand.create_function(args, code) // Create anonymous function
244
php.funchand.function_exists(funcName) // Check if function exists
245
php.funchand.get_defined_functions() // Get defined functions
246
```
247
248
#### Internationalization Functions (2 functions)
249
```javascript { .api }
250
php.i18n.i18n_loc_get_default() // Get default locale
251
php.i18n.i18n_loc_set_default(name) // Set default locale
252
```
253
254
#### Information Functions (6 functions)
255
```javascript { .api }
256
php.info.assert_options(what, value) // Assert configuration options
257
php.info.getenv(varname) // Get environment variable
258
php.info.ini_get(varname) // Get configuration option
259
php.info.ini_set(varname, newvalue) // Set configuration option
260
php.info.set_time_limit(seconds) // Set execution time limit
261
php.info.version_compare(v1, v2, operator) // Compare version strings
262
```
263
264
#### Miscellaneous Functions (2 functions)
265
```javascript { .api }
266
php.misc.pack(format, ...args) // Pack data into binary string
267
php.misc.uniqid(prefix, moreEntropy) // Generate unique identifier
268
```
269
270
#### Net Gopher Functions (1 function)
271
```javascript { .api }
272
php['net-gopher'].gopher_parsedir(dirent) // Parse gopher directory entry
273
```
274
275
#### Regular Expression Functions (4 functions)
276
```javascript { .api }
277
php.pcre.preg_match(regex, str) // Perform regex match
278
php.pcre.preg_quote(str, delimiter) // Quote regex characters
279
php.pcre.preg_replace(pattern, replacement, string) // Regex search and replace
280
php.pcre.sql_regcase(str) // Case-insensitive regex
281
```
282
283
#### Xdiff Functions (2 functions)
284
```javascript { .api }
285
php.xdiff.xdiff_string_diff(oldData, newData, contextLines, minimal) // Create diff
286
php.xdiff.xdiff_string_patch(originalStr, patch, flags, errorObj) // Apply patch
287
```
288
289
#### XML Functions (2 functions)
290
```javascript { .api }
291
php.xml.utf8_decode(strData) // Decode UTF-8 strings
292
php.xml.utf8_encode(argString) // Encode strings to UTF-8
293
```
294
295
## Usage Patterns
296
297
### Function Import Patterns
298
299
```javascript
300
// Full module import
301
const locutus = require('locutus');
302
locutus.php.strings.strlen('test');
303
304
// Category import
305
const phpStrings = require('locutus/php/strings');
306
phpStrings.strlen('test');
307
308
// Individual function import
309
const strlen = require('locutus/php/strings/strlen');
310
strlen('test');
311
```
312
313
### Common Use Cases
314
315
```javascript
316
const locutus = require('locutus');
317
318
// Data processing pipeline
319
const processUsers = (users) => {
320
return users
321
.map(user => ({
322
...user,
323
name: locutus.php.strings.trim(user.name),
324
email: locutus.php.strings.strtolower(user.email)
325
}))
326
.filter(user => locutus.php.var.is_string(user.name) && user.name.length > 0);
327
};
328
329
// Date formatting
330
const formatDate = (timestamp) => {
331
return locutus.php.datetime.date('Y-m-d H:i:s', timestamp);
332
};
333
334
// Array manipulation
335
const mergeAndSort = (...arrays) => {
336
const merged = locutus.php.array.array_merge(...arrays);
337
locutus.php.array.sort(merged);
338
return merged;
339
};
340
```