Match and split of an Array of String PHP - php

I'm having troubles finding the code for this:
I have this array:
$filtros['code'] = 1
$filtros['name'] = 'John'
$filtros['formacion_c_1'] = 2
$filtros['formacion_c_2'] = 1
$filtros['formacion_c_3'] = 2
And I need to catch the number of each "formacion_c_{number}" and his value
echo "The Formation number {number} has the value $filtros[formacion_c_{number}]";
the result that I need is something like :
The Formation number 1 has the value 2.
The Formation number 2 has the value 1.
The Formation number 3 has the value 2.
surely the solution is with some preg_split or preg_match, but I can't handle this

foreach($filtros as $key=>$val){
if(preg_match('/^formacion_c_(\d)+$/', $key, $match) === 1){
echo "The Formation number {$match[1]} has the value $val";
}
}
Demo: http://ideone.com/iscQ7

Why don't you use multidimensional arrays for this?
Instead of:
filtros['formacion_c_1'] = 2
filtros['formacion_c_2'] = 1
filtros['formacion_c_3'] = 2
Why not:
filtros['formacion_c']['1'] = 2
filtros['formacion_c']['2'] = 1
filtros['formacion_c']['3'] = 2
[edit]
I noticed in the comments you said you get this array from a form. You can have multidimensional arrays in HTML forms.
[/edit]
If you can't change the code I guess you could loop through each element and compare the key:
$keyStart = 'formacion_c_';
foreach($filtros as $key => $value) {
if(strstr($key, $keyStart)) {
$id = str_replace($keyStart, '', $key);
}
}

Related

How to seprate numeric value from charcter using 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
)

How can count duplicate array value in php?

I have an array with duplicate values.
I want print all items but also for duplicate value, I want print a number too.
Like this:
$arr = array('sara','jorj','sara','sara','jorj','eli','ana')
foreach($arr as $name)
{
echo $name;
}
How can print this result:
sara
jorj
sara-2
sara-3
jorj-2
eli
ana
This should work for you:
Here I first use array_slice() to get an array of all elements which are before the current element of the iteration, e.g.
iteration value | sliced array
-----------------------------------
sara | []
jorj | [sara]
Then I use this array with array_filter(), to only keep the values with are equal to the current iteration value, so I can tell how many of the same values are in the array before the current value.
Now I simply have to count() how many there are and if there are more than 1 we also print it in the output.
Code:
$arr = array('sara','jorj','sara','sara','jorj','eli','ana');
foreach($arr as $key => $name) {
$count = count(array_filter(array_slice($arr, 0, $key), function($v)use($name){
return $v == $name;
})) + 1;
echo $name . ($count > 1 ? " - $count" : "") . PHP_EOL;
}
output:
sara
jorj
sara - 2
sara - 3
jorj - 2
eli
ana
Maybe Im little bit late to this answer, but heres my attempt
$arr = array('sara','jorj','sara','sara','jorj','eli','ana');
$tmp = array();
foreach ($arr as $value) {
if (!isset($tmp[$value]) ) {
// if $value is not found in tmp array
// initialize the value in tmp array and set to 1
$tmp[$value] = 1;
echo $value;
}
else {
// found the value in tmp array
// add 1 to the value in tmp array
// output its current total count of this value
$tmp[$value] += 1;
echo "$value-", $tmp[$value];
}
echo "<br>";
}
output:
sara
jorj
sara-2
sara-3
jorj-2
eli
ana
This actually has the same output of array_count_values, but broken into pieces of how it forms...I think

php array insert and print

This is a part of my PHP program.
//for example: $rec_count = 30
$totalpages=(int)$rec_count/10;
$index=0;
$pageslink[$totalpages]='';
while($index <= $totalpages ){
$pageslink['index']=$index;
echo '<br>Index: '.$index.'<br>';
echo '<br>Page '.$pageslink['index'].' ';
$index++;
}
print_r($pageslink);
It comes out like this:
Index: 0
Page 0
Index: 1
Page 1
Index: 2
Page 2
Index: 3
Page 3 Array ( [3] => [index] => 3 )
Its supposed to be pageslink[0] = 1; pageslink[1 ]= 2; pageslink[3] = 3; But When I print_r() the pageslink array , only 3 as a value. I've been trying to find out why only 3 is inserted as value in array.
I am a beginner, so thank you in advance for your help. It will be much appreciated.
In the short version of this answer, arrays in PHP start counting from 0, not 1. So on the first loop it would be 0 and the second loop it would be 1 and so on.
You're using
$pageslink['index'] = $index;
Meaning you set the item with the named key 'index' in your array to the value of your variable $index, instead of using $index as your key.
In PHP (and many other languages) you can refer to an item in an array with its index number (0, 1, 2, etc.) or by a word (named key).
For example:
$myArray = ['John', 'London'];
echo $myArray[0]; // John
echo $myAray[1]; // London
or
$myArray = ['name' => 'John', 'city' => 'london'];
echo $myArray['name']; // John
echo $myArray['city']; // London
What you are doing now is setting the same item in your array (the item you're calling index) to a new value every loop, overwriting its old value. So after all the loops you'll only have the last value saved.
You want something like this:
$pageslink[$index] = $index + 1;
Which will translate to:
$pageslink[0] = 1; // first loop
$pageslink[1] = 2; // second loop
$pageslink[2] = 3; // third loop
By the way, a for loop would be cleaner in your example code:
$rec_count = 30
$totalpages=(int)$rec_count/10;
$pageslink = array(); // this is how to create an array, not with ''
for($i=0;i<$totalpages;$i++){
$pageslink[] = $i;
}
print_r($pageslink);
You over complicate the code here, try:
$totalpages=(int)$rec_count/10;
$index=0;
$pageslink = array();
while($index <= $totalpages ){
$pageslink[]=$index+1;
echo '<br>Index: '.$index.'<br>';
echo '<br>Page '.$pageslink[$index].' ';
$index++;
}
print_r($pageslink);
But this code is very weird. You just create array of n elements.
Could you explain what do you try to achieve here?

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)
);
}

php array_rand function with foreach

This code picks 2-6 pitches from the $vec array. I'd like to echo out each individual pitch, but interestingly enough, it gives me the numeric values of the placement of the pitch in the array (ie: 2 5 6 instead of D F F#)
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec,$pick);
foreach ($random_keys as $pitch){
echo $pitch; echo "<br>";
}
Why is it doing this and how can I get the pitches instead of the numbers?
Try this:
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec, $pick);
foreach ($random_keys as $key) {
echo $vec[$key], '<br />';
}
From array_rand() documentation:
Return value
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

Categories