Convert From Javascript Syntax To Php Syntax And From Php To Javascript
STRING MANAGEMENT
Check whether it is a string
JAVASCRIPT
typeof(custom_string1)==”string”
PHP
is_string(custom_string1);
========================
Return length of string
JAVASCRIPT
custom_string1.length
PHP
strlen(custom_string1);
======================
From Ascii custom_number return its char and vice versa
JAVASCRIPT
String.fromCharCode(custom_fromNum)
custom_fromChar.charCodeAt(0)
fromCharCode is invoked using the String constructor as such, namely with a capital S.
charCodeAt requires a string concatenated to it by a dot; pass its argument as zero to mean you want the code of the first char in the string, example:
“y”.charCodeAt(0)
PHP
chr(custom_fromNum);
ord(custom_fromChar);
=====================
Convert to upper or lower case a string
JAVASCRIPT
custom_string1.toLowerCase()
custom_string1.toUpperCase()
PHP
strtolower(custom_string1);
strtoupper(custom_string1);
=======================
Return numerical index of the first instance of a substring position within a wider string
JAVASCRIPT
custom_string1.indexOf( custom_string2, custom_fromNum )
Upon failure (string 2 not present within custom_string1, returns -1)
To make is case insensitive:
custom_string1.toLowerCase().indexOf( custom_string2.toLowerCase(), custom_fromNum )
PHP
strpos( custom_string1, custom_string2, custom_fromNum );
Upon failure (string 2 not present within custom_string1, returns false; since false is the same as zero -fisrt position in the string- to check whether strpos has returned false, do not use comparison check == but the identity check: === namely if
strpos(blabla)===false )
To make it case insensitive use:
stripos( custom_string1, custom_string2, custom_fromNum );
note the i: stripos
==========================
Find the char at a given numerical index
JAVASCRIPT
custom_string1.charAt(custom_number)
PHP
substr(custom_string1, custom_number, 1);
$custom_string1[custom_number];
php, unlike javascript, allows for addressing a string like an array of chars too, that is through square brackets indexing of the string itself.
Return numerical index of the last instance of a substring position within a wider string
====================================
JAVASCRIPT
custom_string1.lastIndexOf( custom_string2, custom_fromNum )
Upon failure (string 2 not present within custom_string1, returns -1)
To make is case insensitive:
custom_string1.toLowerCase().lastIndexOf( custom_string2.toLowerCase(), custom_fromNum )
PHP
For Php 5 onward you can use:
strrpos(custom_string1, custom_string2, custom_fromNum);
Upon failure returns boolean false, to discriminate it from zero use for comparisons the === operator.
The case insensitive version is:
strripos(custom_string1, custom_string2, custom_fromNum);
note the i in the function name.
=================================
Return substring
JAVASCRIPT
custom_string1.substring( custom_fromNum, toNum )
custom_string1.substr( custom_fromNum, length )
PHP
substr( custom_string1, custom_fromNum, (toNum-custom_fromNum) );
substr( custom_string1, custom_fromNum, custom_lengthOfItem);
PHP
substr( custom_string1, custom_fromNum, custom_lengthOfItem );
JAVASCRIPT
custom_string1.substr(custom_fromNum, length)
custom_string1.substring( custom_fromNum, (custom_fromNum+length) )
PHP
strstr( custom_string1, custom_string2 );
JAVASCRIPT
custom_string1.substring( custom_string1.indexOf(custom_string2) )
============================
Split a string
JAVASCRIPT
custom_string1.split(stringSplitter)
PHP
explode(stringSplitter, custom_string1);
explode does not accept an empty splitter such as “” in php, though javascript would accept it. To split by an empty splitter, use in PHP
preg_split( “//”, custom_string1);
the two forward slashes are the delimiters of a regular expression, and encapsulating in this case nothing they amount to an empty splitter.
Note that with preg_split the hidden chars such as those of starting line or new line are included, therefore the first entry [0] of the returned splitted array would be an empty slot. Any break of line would then be reflected as two apparently “empty” returned array slots, one for the carriage return hidden char, the other for the new line hidden char.
=================================
Replace instances in a string
JAVASCRIPT
custom_string1.replace( custom_findThis, custom_replaceWithThis )
custom_string1.replace( custom_regularExpression, custom_replaceWithThis )
PHP
str_replace( custom_findThis, custom_replaceWithThis, custom_string1 );
this function replaces all instances.
preg_replace( custom_regularExpression, custom_replaceWithThis, custom_string1 );
custom_regularExpression must be in between quotes, unlike JAVASCRIPT
“/regexp here/”
PHP
substr_replace( custom_string1, custom_replaceWithThis, custom_fromNumIndex, custom_lengthOfItem );
JAVASCRIPT
custom_string1.replace( custom_string1.substring( custom_fromNumIndex, (custom_fromNumIndex+length) ), custom_replaceWithThis )
==================================
Strip Tags from a String
JAVASCRIPT
In Javascript we use a replacement, for no specific method is available for this task as in PHP
custom_string1=custom_string1.replace(/<[^>]+>/g, ”);
PHP
custom_string1=striptags(custom_string1);
==============================
Replace instances in a string
JAVASCRIPT
custom_string1.replace( custom_findThis, custom_replaceWithThis )
custom_string1.replace( custom_regularExpression, custom_replaceWithThis )
PHP
str_replace( custom_findThis, custom_replaceWithThis, custom_string1 );
this function replaces all instances.
preg_replace( custom_regularExpression, custom_replaceWithThis, custom_string1 );
custom_regularExpression must be in between quotes, unlike JAVASCRIPT
“/regexp here/”
PHP
substr_replace( custom_string1, custom_replaceWithThis, custom_fromNumIndex, custom_lengthOfItem );
JAVASCRIPT
custom_string1.replace( custom_string1.substring( custom_fromNumIndex, (custom_fromNumIndex+length) ), custom_replaceWithThis )
=============================
ARRAY MANAGEMENT
Is that an array?
JAVASCRIPT
typeof(custom_array1)==”object”
PHP
is_array(custom_array1)
==================================
Length of an array
JAVASCRIPT
custom_array1.length
PHP
sizeof(custom_array1);
=============================
Join array entries into a string
JAVASCRIPT
custom_array1.join(custom_stringJoiner)
PHP
implode(custom_stringJoiner, custom_string1);
Return length of string
JAVASCRIPT
custom_array1.concat(custom_array2, custom_array3…)
This javascript method will not concatenate associative arrays namely arrays whose indexes are not uniquely numerical.
PHP
array_merge(custom_array1, custom_array2, custom_array3…);
array_merge_recursive(custom_array1, custom_array2, custom_array3…);
This latter php method will concatenate associative arrays too namely arrays whose indexes are not uniquely numerical. From php.net:
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later custom_value will not overwrite the original custom_value, but will be appended.
=======================================
Pop, push, shift, unshift on arrays
JAVASCRIPT
custom_array1.shift()
custom_array1.unshift(custom_value)
custom_array1.pop()
custom_array1.push(custom_value)
PHP
array_shift(custom_array1);
array_unshift(custom_array1, custom_value);
array_pop(custom_array1);
array_push(custom_array1, custom_value);
==================================
Reverse an array
JAVASCRIPT
custom_array1.reverse()
PHP
array_reverse(custom_array1);
This function accepts a second parameter, if passed as keyword true the arry is reversed but the indexes still the same.
To reset the indexes of an array in PHP
custom_array1=array_values(custom_array1);
====================================
Slice an array
JAVASCRIPT
custom_array1.slice(custom_startIndex, custom_endIndex)
Original custom_array1 not affected, the sliced subsegment is released as an array of its own.
custom_array1.splice(custom_startIndex, custom_lengthOfItem)
Original custom_array1 is affected. This latter function allows for a third argument, which must be an array: if provided, in the original array the spliced (removed, for original is affected) subsection is just replaced with it.
Note that in javascript the third argument is an index with slice and a length with splice.
PHP
array_slice( custom_array1, custom_startIndex, (custom_endIndex-custom_startIndex) );
Original not affected.
array_splice( custom_array1, custom_startIndex, custom_lengthOfItem );
Original custom_array1 is affected. This latter function allows for a fourth argument, which must be an array: if provided, in the original array the spliced (removed, for original is affected) subsection is just replaced with it.
PHP
array_slice( custom_array1, custom_startIndex, custom_lengthOfItem );
array_splice( custom_array1, custom_startIndex, custom_lengthOfItem );
JAVASCRIPT
custom_array1.slice(custom_startIndex, (custom_startIndex+custom_lengthOfItem))
custom_array1.splice(custom_startIndex, custom_lengthOfItem)
==========================================
Sort an array
JAVASCRIPT
custom_array1.sort(custom_optionalFunction)
PHP
sort(custom_array1);
You have a wide family of sorters in php as such:
rsort ; Sort an array in reverse order
ksort ; Sort an array by key
krsort ; Sort an array by key in reverse order
natsort ; Sort an array using a natural order algorithm (what in javascript we called custom_optionalFunction)
natcasesort ; Sort an array using a case insensitive natural order algorithm (what in javascript we called custom_optionalFunction)
usort(custom_array1, custom_optionalFunction) ; Sort an array with a user-defined custom_optionalFunction
uksort(custom_array1, custom_optionalFunction) ; Sort an array by keys with a user-defined custom_optionalFunction
uasort(custom_array1, custom_optionalFunction) ; Sort an array with a user-defined custom_optionalFunction
======================================
NUMBER MANAGEMENT
Is it a custom_number?
JAVASCRIPT
isNaN(custom_number)
returns true if it is not a custom_number. Yet also numerical strings (so called literal numbers, say: “12″) are reported as numbers.
Note that the typeof of a non custom_number returned by isNan is, confusing enough: “custom_number”
PHP
is_nan(custom_number);
is_numeric(custom_number);
returns true if it is not a custom_number. Yet also numerical strings (so called literal numbers, say: “12″) are reported as numbers.
is_integer(custom_number);
returns false if custom_number has floating digits. Literal numbers (in between quotes) return false.
is_double(custom_number);
returns false if custom_number has no floating digits. Literal numbers (in between quotes) return false.
====================================
Convert strings into numbers
JAVASCRIPT
parseInt(custom_string1)
parseFloat(custom_string1)
PHP
(integer)custom_string1;
(double)custom_string1;
The procedure above is called data type casting.
========================================
Round a custom_number, get its absolute custom_value
JAVASCRIPT
Math.floor(custom_number); Math.ceil(custom_number); Math.round(custom_number);
Mat.abs(custom_number);
PHP
ceil( custom_number ); floor( custom_number ); round( custom_number );
abs( custom_number );
===================================
Max and custom_min or random numbers
JAVASCRIPT
Math.max(custom_number1, custom_number2)
Math.min(custom_number1, custom_number2)
(Math.random()*(custom_max-custom_min))+custom_min
custom_min and custom_max are optional. If omitted, this function just generates a fractional custom_number included between 0 and 1. To produce only non fractional numbers you may use:
Math.round(
(Math.random()*(custom_max-custom_min))+custom_min
)
PHP
max(custom_number1, custom_number2);
min(custom_number1, custom_number2);
mt_rand(custom_min, custom_max);
custom_min and custom_max are optional. If omitted, this function just generates a custom_number up to ten digits long.
Prior to Php 4.2.0 you have also to feed the seed by calling first:
mt_srand((double)microtime()*1000000)
just like that!
===========================================
Pow and squares
JAVASCRIPT
Math.pow(custom_number, custom_power)
Math.sqrt(custom_number)
Math.pow(custom_number, 1/custom_root)
Above is the x custom_root of a custom_number, for Math.sqrt provides only square roots.
PHP
pow(custom_number, custom_power);
sqrt(custom_number);
pow(custom_number, 1/custom_root);
Above is the x custom_root of a custom_number, for sqrt provides only square roots.
================================
Trigonometric functions
JAVASCRIPT
Math.sin(); Math.cos(); Math.tan();
Math.asin(); Math.acos(); Math.atan();
PHP
sin(); cos(); tan();
asin(); acos(); atan();
==================================
Constants and logarhitms
JAVASCRIPT
Math.PI; Math.log(custom_value)
PHP
pi();
log(custom_value);
====================================
FUNCTION MANAGEMENT
Return length of string
JAVASCRIPT
typeof(custom_functionName)==”function”; //is it a function?
This must be called inside the function custom_functionName:
custom_functionName.arguments.length;
custom_functionName.arguments; //array of args
custom_functionName.arguments[custom_number];
PHP
function_exists(“custom_functionName”); //is it a function?
This must be called inside the function custom_functionName:
func_num_args();
func_get_args(); //array of args
func_get_arg(Number)
А зачем? насчет более интересной двигаться дальше
Проще надо говорить и все будет хорошо
Просто по тому не буду критиковать что было потрачено время, а надо бы)
Привет блогерам, кто-то из Москвы есть? Давайте тему создадим отдельную.
Спасибо, неплохая подборка материала, меня так порадовала статья. только почему не ставите ссылку на первоисточник?
С наилучшими пожеланиями вашему сайту
Are you facing financial shortfalls in the mid of the month? Have urgent pending bills to pay off? Trapped with unforeseen financial exigency trouble? Do you over with payday? Stop thinking and start acting!
Работа над сайтом меня реально порадовала. Благодарю за проделанную работу
Лучше бы вы написали работу эту попроще, имхо лучше было бы
Обожаю ваши публикации. Побольше бы этих публикаций и все будет отлично
прикольно!. Ничего себе! там реально полезные мысли
Люблю ваш сайт за то что тут актуальные и полезные новости. Респектище вам!!!
Жду от вас более полной новости.Т.к. это не полностью
приятнее, конечно:) Ого, вот это да! двигаться дальше
А зачем? я немного не понял, если честно Результат вас устраивает
обязательно ли регистрироватся на вашем сайте чтобы комменты опубликовали?
Сие творение по нраву мне. Автор постарался наславу
Некоторые моменты хотелось бы уточнить 6м
С нетерпением жду продолжения темки 8в
Мне очень понравился подход к раскрытию темы 7с
С огромным удовольствием просмотрел статьи 6ф
Складывается устойчивое впечатление о том что автор прошареный человек. Так все хорошо написал
Вы меня просто поразили. Это превосходный материал. Спасибо
Выражаю thanks юзеру этого сайта. Наконец то я нашла что надо
Прикольно пишете, но есть много вопросов 6ы
Узнал много нового и интересного, спасибо 6т
Мне очень понравился подход автора к подбору материала 5м
Очень понравился стиль автора, жду ещё 5м
С нетерпением жду новых материалов 5ч
Прикольно почитать, но кое-что можно и поподробнее объяснить 5м
Понравилась темка, очень познавательно 5м
Понравился стиль автора, неординарный 5с
Даже не думал, что так затянет чтение этого материала 6п
Некоторые моменты хотел уточнить 5а
Получил удовольствия от прочитанного материала 5а