How to seprate numeric value from charcter using PHP - php

I need one help.i need to separate numeric value from character using PHP.I am explaining my code below.
$subcatid=a1,a2,4,5
here i have some value with comma separator i need here separate numeric value(i.e-4,5) first and push them into a array then i have to separate rest numeric value from character(i.e-1 from a1,2 from a2) and push those separated value into another array.Please help me.

Try this
<?php
$subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
$onlynum_subcatid = array_filter($subcatid_arr, 'is_numeric');
$onlynum = implode(",",$onlynum_subcatid );
echo "Only Number : ".$onlynum;
$notnum_subcatid = array_diff($subcatid_arr,$onlynum_subcatid );
$notnum = implode(",",$notnum_subcatid );
echo "\nNot Number : ".$notnum;
?>
Output is :
Only Number : 4,5
Not Number : a1,a2
check here : https://eval.in/539059

Use this code
$subcatid="a1,a2,4,5";
$strArray = explode(',',$subcatid);
$intArr = array();
foreach($strArray as $key=>$value):
if(preg_match('/^[0-9]*$/',$value)):
$intArr[]=$value;
else:
$str2Arr = str_split($value);
foreach($str2Arr as $keyStr=>$lett):
if(preg_match('/^[0-9]*$/',$lett)):
$intArr[]=$lett;
endif;
endforeach;
endif;
endforeach;
var_dump($intArr);

in this code you can expect your result. Do process with the $number, $char array as required
<?php
$subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
for($i=0;$i<sizeof($subcatid_arr);$i++){
if(is_numeric($subcatid_arr[$i])){
$number[]=$subcatid_arr[$i];
}
else{
$char[]=$subcatid_arr[$i];
}
}
print_r($number);// 4,5
print_r($char);// a1,a2
?>

If I am understanding correctly, you want to put all of the original numeric values into a single array and then filter just the numeric parts of the leftovers and put them in to a second array.
If this is correct then I believe this should do what you want.
<?php
$subcatid = 'a1,a2,4,5';
$subcat_array = explode(",",$subcatid);
$subNums1 = [];
$subNums2 = [];
foreach($subcat_array as $item) {
if(is_numeric($item)) {
// This pushes all numeric values to the first array
$subNums1[] = $item;
} else {
// This strips out everything except the numbers then pushes to the second array
$subNums2[] = preg_replace("/[^0-9]/","",$item);
}
}
print_r($subNums1);
print_r($subNums2);
?>
This will return:
Array (
[0] => 4
[1] => 5
)
Array (
[0] => 1
[1] => 2
)

Related

PHP match comma separated string with array value but not in exact order

I have a possibly simple query but couldn't find an exact solution anywhere.
There is a comma separated string such as 1,3 and an array with values such as 1,3,2 OR 3,1,4. I need a function that when I try to search this string in the array, it returns TRUE for both the records as the number 1 & 3 exists in both array values but just in different order.
I have tried using array_search, strpos and even explode to first make the string in an array followed by array_intersect to intersect both arrays hoping to get a positive match but always only returns the array with values 1,3,2 and not 3,1,4.
Any suggestions or pointers would be extremely helpful.
Many thanks in advance.
======================
PS: Here's my code
//Enter your code here, enjoy!
$st_array = array();
$st_data1['id'] = 1;
$st_data1['title'] = 'Jane doe';
$st_data1['disk'] = '1,3,2';
array_push($st_array, $st_data1);
$rc_disk_id = '1,3';
$st_data2['id'] = 2;
$st_data2['title'] = 'Jane Smith';
$st_data2['disk'] = '3,1,4';
array_push($st_array, $st_data2);
foreach($st_array as $st_data) {
$rc_disk_ids = explode(",",$rc_disk_id);
$match = array_intersect($rc_disk_ids, $st_data);
if (!empty($match)) {
echo "\nFound\n";
print_r($st_data);
}
else {
echo "Nope!";
}
}
Your code is very close. You need to also explode the list of disk ids in $st_data, and then use array_diff to check whether all of the values in $rc_disk_ids are present in that list:
foreach($st_array as $st_data) {
$rc_disk_ids = explode(",",$rc_disk_id);
$st_disk_ids = explode(',', $st_data['disk']);
$match = array_diff($rc_disk_ids, $st_disk_ids);
if (empty($match)) {
echo "\nFound\n";
print_r($st_data);
}
else {
echo "Nope!";
}
}
Output for your sample data:
Found
Array
(
[id] => 1
[title] => Jane doe
[disk] => 1,3,2
)
Found
Array
(
[id] => 2
[title] => Jane Smith
[disk] => 3,1,4
)
Demo on 3v4l.org
Maybe you can try searching for the string instead of comparing arrays.
$strArr = explode(",", "1,3");
$arrToBeSearched = ["1", "3", "2"];
foreach($strArr as $val){
if(!in_array($val, $arrToBeSearched)){
return FALSE;
}
}
// If it reaches here, then all values in
//the $strArr where found in the
//$arrToBeSearched
return TRUE;

PHP Multidimensional Array Length

This is a multidimensional PHP array.
$stdnt = array(
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94),
);
I can find out the length of the array. That means
count($stdnt); // output is 4
[
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94)
] `
But can't get the internal array length.
How can I ?
If you are assuming the subarrays are all the same length then:
$count = count($stdnt[0]);
If you don't know the keys:
$count = count(reset($stdnt));
To get an array with a separate count of each of the subarrays:
$counts = array_map('count', $stdnt);
The other way to count internal array lengths is to iterate through the array using foreach loop.
<?php
$stdnt = array(
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94),
);
foreach($stdnt as $s)
{
echo "<br>".count($s);
}
?>
please use sizeof function or count function with recursive
e.g echo (sizeof($stdnt,1) - sizeof($stdnt)) ; // this will output you 9 as you want .
first sizeof($stdntt,1) ; // will output you 13 . count of entire array and 1 mean recursive .
According to the hint from Meaning of Three dot (…) in PHP, the following code is what I usually use for this case:
$stdnt = array(
array("Arafat", 12210261, 2.91),
array("Rafat", 12210262, 2.92),
array("Marlin", 12210263, 2.93),
array("Aziz", 12210264, 2.94),
);
echo count(array_merge(...$stdnt));
The Splat operator "..." will only work,
Only if the first level keys are in integer, ie, not "strings"
PHP > 5.6
// You may try as per this sample
$cars=array(
array("volvo",43,56),
array("bmw",54,678)
);
$mySubSize=sizeof($cars);
for ($i=0;$i<$mySubSize;$i++) {
foreach ($cars[$i] as $value) {
echo "$value <br>";
}
}

How to find the first, second, third etc numbers of an array

I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:
$numbers = range(1,4);
Then I shuffle with this:
shuffle($numbers);
Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:
foreach($numbers as $number){
$test = array("first"=>"$number");
echo $test['first'];
}
What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:
foreach($numbers as $number){
$test = array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth']," <br>";
}
This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.
If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)
You can use sizeof() it is return size of array size, and pass the key value manually. Like-
echo $numbers[0];
echo $numbers[1];
echo $numbers[2];
Here is a full code, try it
$numbers = range(1,4); //generate four numbers
shuffle($numbers); //shuffle them
$test = array(); //create array for the results
$words = array("1st", "2nd", "3rd", "4th","5th"); //create your array keys
$i=0;
foreach($numbers as $number){
$test[] = array($words[$i]=>$number); //add your array keys & values
$i++;
}
print_r($test); //show your results
If my understanding is correct you have an array and you want certain values from within it?
Then why not just use the array keys:
$array = array('peach','pear','apple','orange','banana');
echo $array[0]; // peach
echo $array[1]; // pear
echo $array[2]; // apple
Or you could loop through the array like so:
foreach ($array as $arrayKey => $arrayValue) {
// First value in the array is now below
echo $arrayKey; // 0
echo $arrayValue; // peach
}
You can also check if a value is in an array like so:
if (in_array('orange', $array)) {
echo 'yes';
}
Edit:
// Our array values
$array = array('peach','pear','apple','orange','banana');
// We won't shuffle for the example, we need expected results
#$array = shuffle($array);
// We want the first 3 values of the array
$keysRequired = array(0,1,2);
// This will hold our results
$storageArray = array();
// So for the first iteration of the loop $arrayKey is going to be 0
foreach ($array as $arrayKey => $arrayValue) {
// If the array key matches one of the values in the required array
if (in_array($arrayKey, $keysRequired)) {
// Store it within the storage array so we know what value it is
$storageArray[] = $arrayValue;
}
}
// Let's see what values have been stored
echo "<pre>";
print_r($storageArray);
echo "</pre>";
Would give you the following:
Array
(
[0] => 'peach'
[1] => 'pear'
[2] => 'apple'
)
Try this:
<?php
$numbers = range(1,4);
shuffle($numbers);
$test = array();
foreach($numbers as $k=>$v){
$test[$k] = $v;
}
echo "<pre>";
print_r($test);
?>
This will give you the output as:
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 1
)
After that you can do:
$myvar["first"] = $test[0];
$myvar["second"] = $test[1];
$myvar["third"] = $test[2];
$myvar["fourth"] = $test[3];
Every array has a key, value pair, if you have an array say:
$myarr = array("a", "b", "c");
then you can access the value "a" as $myarr[0], "b" as $myarr[1] and so on.
In the for loop I am looping through the array with their key and value, this will not only give you the key of the array but also the value associated with that key.
More on Array
Edit:
Improving what Luthando Loot answered:
<?php
$numbers = range(1,4);//generate four numbers
shuffle($numbers);//shuffle them
$test = array();//create array for the results
$words = array("first", "second", "third", "fourth"); //create your array keys
$i = 0;
foreach($numbers as $number){
$test[$words[$i]] = $number;//add your array keys & values
$i++;
}
echo "<pre>";
print_r($test); //show your results
?>
Output:
Array
(
[first] => 4
[second] => 3
[third] => 2
[fourth] => 1
)
use this way
$numbers[0];
$numbers[1];
$numbers[2];
$numbers[3];
Firstly make an array of keys as
$key = ['first','second','third','fourth'];
And then you can simply use array_combine as
$numbers = range(1,4);
shuffle($numbers);
$key = ['first','second','third','fourth'];
$result = array_combine($key,$numbers);
Demo

PHP - Use everything from 1st array, remove duplicates from 2nd?

I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!
For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });
If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}
If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]

Split A String at X, then at Y Value

I have the following code:
$Field = $FW->Encrypt("Test");
echo "<pre>";
print_r($Field);
echo "</pre>";
# $IV_Count = strlen($Field['IV']);
# $Key_Count = strlen($Field['Key']);
# $Cipher_Count = strlen($Field['CipheredText']);
foreach ($Field AS $Keys => $Values){
echo $Keys."Count = ".strlen($Values)."<br><br>";
}
The output is as:
Array
(
[CipheredText] => x2nelnArnS1e2MTjOrq+wd9BxT6Ouxksz67yVdynKGI=
[IV] => 16
[Key] => III#TcTf‡eB12T
)
CipheredTextCount = 44
IVCount = 2
KeyCount = 16
The IV/KeyCount is always returning the same value regardless of the input. But the CipheredTextCount changes depending on the input.. For example:
$Field = $FW->Encrypt("This is a longer string");
The foreach loop returns:
CipheredTextCount = 64
IVCount = 2
KeyCount = 16
and now for my question. Lets take the first example with the TextCount of 44
How can I split a string after implode("",$Field); to display as the original array? an example would be:
echo implode("",$Field);
Which outputs:
ijGglH/vysf52J5aoTaDVHy4oavEBK4mZTrAL3lZMTI=16III#TcTf‡eB12T
Based on the results from the strlen?
It is possible to store the count of the first $Cipher_Count in a database for a reference
My current setup involves storing the key and IV in a seperate column away from the ciphered text string.. I need this contained within one field and the script handles the required information to do the following:
Retrieve The long string > Split string to the original array > Push
array to another function > decrypt > return decoded string.
Why not use serialize instead? Then when you get the data out of the database, you can use unserialize to restore it to an array.
$Combined_Field = implode("",$Field);
echo $str1 = substr($Combined_Field, 0, $Cipher_Count)."<br><br>";
echo $str2 = substr($Combined_Field,$Cipher_Count,$IV_Count)."<br><br>";
echo $str3 = substr($Combined_Field, $IV_Count+$Cipher_Count,$Key_Count);
Or use a function:
function Cipher_Split($Cipher, $Cipher_Count, $KeyCount, $IVCount){
return array(
"Ciphered Text" => substr($Cipher,0,$Cipher_Count),
"IV" => substr($Cipher,$Cipher_Count,$IVCount),
"Key" => substr($Cipher,$IVCount+$Cipher_Count,$KeyCount)
);
}

Categories