sort an array contain number and letter - php

when sort an array with letter and number, like below:
$a = array(0, 1, 'a', 'A');
sort($a);
print_r($a);
the result confuse me like that:
Array ( [0] => a [1] => 0 [2] => A [3] => 1 )
why the '0' between in 'a' and 'A'?

When you do that, the numbers are converted to a string. Number character ASCII values come between the two cases.
The strings are converted to numbers. It takes any number characters at the beginning and drops everything else to compare, unless it finds '.','E', or 'e', which can be used for floating-point conversion. If it finds no numeric characters, it evaluates to zero.

Related

How to split a string into different parts in PHP?

I have 3 strings in PHP which contains a list of test input for a function with two parameters.
I want to parse the strings and get the individual parameter values.
example:
"a,b" => "a", "b"
"/"string_param1/", /"string_param2/"" => "string_param1", "string_param2"
"[list,1], [list,2]" => "[list,1]", "[list,2]"
For strings 1 and 3 you can use the explode function to split the string at the comma like so:
$a = 'a,b';
$a_params = explode(',', $a);
But for the second string you can run str_replace to get rid of unwanted quotes or backslashes so you can use explode.
str_replace() documentation
explode() documentation
You cannot simply use explode() because you have other factor to accommodate.
preg_split() is the function to call when you want to perform a variable explosion.
(*SKIP)(*FAIL) is a very handy technique for this case because it consumes the "protected" substrings and then disqualifies them as possible splitting points.
The , ? (comma - space - questionmark) means that you want to explode on every comma that is optionally trailed by a space.
Code: (Demo)
$test_strings = ['a,b', '/"string_param1/", /"string_param2/"', '[list,1], [list,2]'];
foreach ($test_strings as $string) {
$result[] = preg_split('~(?:\".*?\"|\[[^[]*])(*SKIP)(*FAIL)|, ?~', $string, -1, PREG_SPLIT_NO_EMPTY);
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'a',
1 => 'b',
),
1 =>
array (
0 => '/"string_param1/"',
1 => '/"string_param2/"',
),
2 =>
array (
0 => '[list,1]',
1 => '[list,2]',
),
)

How to split string with special character (�) using PHP

Currently I am trying to split the � the special character which represents %A0 at the URL. However when I use another URL, it doesn't recognize %A0 therefore I need to use %20 which is the standard space.
My question is. Is there a way to explode() special character �? Whenever I try to explode, it always return a single index array with length 1 array.
//Tried str_replace() to replace %A0 to empty string. Didn't work
$a = str_replace("%A0"," ", $_GET['view']);
// Tried to explode() but still returning single element
$b = explode("�", $a);
// Returning Array[0] => "Hello World" insteand of
// Array[2] => [0] => "Hello", [1] => "World"
echo $b[0];
Take a look at mb_split:
array mb_split ( string $pattern , string $string [, int $limit = -1 ] )
Split a multibyte string using regular expression pattern and returns
the result as an array.
Like this:
$string = "a�b�k�e";
$chunks = mb_split("�", $string);
print_r($chunks);
Outputs:
Array
(
[0] => a
[1] => b
[2] => k
[3] => e
)

How to split string into an alphabetic string and a numeric string?

I need to use preg_split() function to split string into alpha and numeric.
Ex: ABC10000 into, ABC and 10000
GSQ39800 into GSQ and 39800
WERTYI67888 into WERTYI and 67888
Alpha characters will be the first characters(any number of) of the string always and then the numeric(any number of).
using preg_match
$keywords = "ABC10000";
preg_match("#([a-zA-Z]+)(\d+)#", $keywords, $matches);
print_r($matches);
output
Array
(
[0] => ABC10000
[1] => ABC
[2] => 10000
)
This is a tiny task. Use \K with matching on an capital letters in a character class using a one or more quantifier:
Code:
$in='WERTYI67888';
var_export(preg_split('/[A-Z]+\K/',$in));
Output:
array (
0 => 'WERTYI',
1 => '67888',
)

Split a string into an array, and assign a value based on their letter?

I'm not asking you to code it for me or anything, snippets of code or just pointing me in the right direction will help me out a lot.
This is what I'm basically trying to do, you have the word "abcdefg"
I want it to split up the string into an array (or whatever works best?) , then assign a value based on what letter is stored into the array. (based on the alphabet , a = 1 , b = 2 , c = 3 , z = 26)
so abcdefg will turn into something like
$foo("a" => 1, "b" =>2, "c" => 3, etc..);
but obviously if "abcdefg" was "zaj", the array would be "z" => 26 , "a" => 1 , "j" => 10
Basically, convert a string of letters into their alphabetical num value sorta?
The functions you need are:
str_split
ord
array_map
With those functions you can solve this problem in a very small number of lines of code.
Steps that has been put to implement this.
Generate an alphabet array (alphabets starting from index 1)
Get the value which which you want to generate as an array.
Split them up with str_split
Using a foreach construct search them in the earlier alphabet array that was created using array_search
When found just , just grab their key and value and put it in the new array.
<?php
$alph[]='Start';
foreach(range('a','z') as $val)
{
$alph[]=$val;
}
$makethisvalasarray='zaj';
$makethisvalasarray=str_split($makethisvalasarray);
foreach($makethisvalasarray as $val)
{
$newarr[$val]=array_search($val,$alph);
}
print_r($newarr);
OUTPUT :
Array
(
[z] => 26
[a] => 1
[j] => 10
)

why i am getting wrong array count in php

$array = array (0.1 => 'a', 0.2 => 'b');
echo count ($array);
It overwrites first array element by second, just because, I used float with 0.
And hence output of above code is 1, instead of 2.
Why PHP round array index down to 0 ?
The array keys are interpreted as numeric, but numeric keys must be integers, Therefore, both float values are cast (truncated) to integer zero and 0.2 overwrites 0.1.
var_dump($array);
array(1) {
[0]=>
string(1) "b"
}
Make the array keys strings if you want to use non integer values:
$array = array ("0.1" => 'a', "0.2" => 'b');
echo count($array);
// 2
array(2) {
["0.1"]=>
string(1) "a"
["0.2"]=>
string(1) "b"
}
Only integer is allowed as key of the array.
See what we get if I print_r($array):
Array ( [0] => b )
However you can do like this:
$array = array ('0.1' => 'a', '0.2' => 'b');
Now print_r says this:
Array ( [0.1] => a [0.2] => b )
Array indices cannot be floats. They must be either integers or strings. If you would try to var_dump($array); you would see that your array looks something like this:
array(1) {
[0]=> string(1) "b"
}
You are effectively trying to set value for key 0 twice.
You cannot use floats as numeric keys. 0.1 and 0.2 both get converted to 0
Either you have to use integers or strings. Therefore, your options are:
$array = array ('0.1' => 'a', '0.2' => 'b');
Or:
$array = array (1 => 'a', 2 => 'b');
Let's see what the PHP's own excellent manual says about arrays (emphasis mine):
The key can either be an integer or a string. The value can be of any
type.
Additionally the following key casts will occur: [...] Floats are also cast to
integers, which means that the fractional part will be truncated.
So, if you look at your array:
<?php
$array = array (0.1 => 'a', 0.2 => 'b');
var_dump($array); // let's see what actually *is* in the array
echo count ($array);
you'll get this back:
array(1) {
[0]=>
string(1) "b"
}
1
So, first your array is { 0 => 'a' }, then becomes { 0 => 'b' }. The computer did exactly what you asked it to, even if not what you intended.
Possible solution: pass the array keys as strings - there is no conversion to int, and it works as expected.
$array = array ('0.1' => 'a', '0.2' => 'b');
You must use quote on non-integer keys
$array = array ('0.1' => 'a', '0.2' => 'b');
echo count($array);
You are storing 'a' into the 0.1th element and 'b' into the 0.2nd element. This is impossible. Array indexes must be integers.
Perhaps you are wanting to use associative arrays?
$array = array ('0.1' => 'a', '0.2' => 'b');
As per the php.net document on arrays for having keys:
Additionally the following key casts will occur:
Floats are also cast to integers, which means that the fractional part
will be truncated. E.g. the key 8.7 will actually be stored under 8.
i tried dumping and interpreting the result... 0.1 and 0.2 will be interpreted as 0 and the latter overwrites the former, end result is that the array key remains 0 and value is set as b.
Hence there's nothing wrong with this behavior.
its because floats are casted to integers, so the second entry overwrites the first.
Actually you are doing this:
$array = array (0 => 'a', 0 => 'b');
echo count ($array);
Php.net Array:
"Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8."

Categories