Getting numbers only from an array [duplicate] - php

This question already has answers here:
Extract a single (unsigned) integer from a string
(23 answers)
Closed 6 years ago.
i have this array in php
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
i wanted to strip all alphabets and dots in the string remains only number like
$name = array("18","16","17","19");
how do i achieve that can some one please guide me how to do it in PHP language

Try this,use preg_replace
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
foreach($name as $val)
{
$new_name[] = preg_replace('/\D/', '', $val);
}
DEMO

You can do it without using Regex by using string replace function (str_replace()):
<?php
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
$myArra = array();
foreach ($name as $key => $value) {
$var = str_replace("page", "", $value);
$var = str_replace(".jpg", "", $var);
$myArra[] = $var; // store all value without text and .jpg
}
print_r($myArra);
?>
Result:
Array
(
[0] => 18
[1] => 16
[2] => 17
[3] => 19
)
Or, if you want to use Regex, than you can use /\d+/ pattern as like:
<?php
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
$myArra = array();
foreach ($name as $key => $value) {
preg_match_all('/\d+/', $value, $matches);
$myArra[] = $matches[0][0]; // store all value without text and .jpg
}
echo "<pre>";
print_r($myArra);
?>
Result:
Array
(
[0] => 18
[1] => 16
[2] => 17
[3] => 19
)

Aside from using str_replace() and preg_replace(), you can use array_map() and filter_val() like so:
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
$name = array_map(function($fv) {
return filter_var($fv, FILTER_SANITIZE_NUMBER_INT);
}, $name);
print_r($name);
Output:
Array
(
[0] => 18
[1] => 16
[2] => 17
[3] => 19
)

A very simplified and native solution from the house of PHP:
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
foreach ($name as $n) {
$num_arr[] = filter_var($n, FILTER_SANITIZE_NUMBER_INT);
}
var_dump($num_arr);
exit();
Outputs:
Array ( [0] => 18 [1] => 16 [2] => 17 [3] => 19 )
enjoy fresh air ;)

<?php
$name = array ("page18.jpg","page16.jpg","page17.jpg","page19.jpg");
$myarray =array();
foreach($name as $key =>$value){
$page_replace= str_replace("page", "",$value); //replace page as a blank
$jpg_replace= str_replace(".jpg","",$page_replace); //replace jpg to blank
$myarray[] =$jpg_replace;//stroing without jpg and page getting resulut as key value pair
}
echo "<pre>";
print_r($myarray);
?>

Related

convert array to one variable with multiple values [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
here is my array .
$myarray = Array
(
[0] = Array
(
[name] = 17
)
[1] = Array
(
[name] = 18
)
[2] = Array
(
[name] = 19
)
)
I want myvar to return this '17,18,19'
$var = '17,18,19';
You can use array_map;
$temp = array_map(function($i){return $i['name'];}, $myarray);
$output = implode(',', $temp);
You can do it in many ways. One way to do it with array_column() and implode()
<?php
$myarray = array(array('name' => 17),array('name' => 18),array('name' => 19));
$one_d = array_column($myarray, 'name');
echo implode(',',$one_d);
?>
DEMO: https://3v4l.org/rCmKR
A simple foreach could also do the trick.
$var = '';
foreach ($myarray as $value) {
$var .= $value['name'].',';
}
$var = substr($var, 0, -1);
echo $var; // 17,18,19

Last letters remove form array in foreach loop

I want to remove the last few letters from an array in a for-each loop. I am trying to show bl_date without /2018. Now its showing 07/10/2018 & 06/30/2018. How can echo like this 07/10 & 06/30?
Array
Array
(
[0] => stdClass Object
(
[id] => 18
[bl_user] => 61
[bl_date] => 07/10/2018
)
[1] => stdClass Object
(
[id] => 17
[bl_user] => 61
[bl_date] => 06/30/2018
)
)
PHP
$resultstr = array();
foreach ($billings as $billing) {
$resultstr[] = $billing->bl_date;
}
echo implode(" & ",$resultstr);
One option is to use substr() to remove the last 5 characters of the string
Like:
$resultstr = array();
foreach ($billings as $billing) {
$resultstr[] = substr( $billing->bl_date, 0, -5 );
}
echo implode(" & ",$resultstr);
This will result to:
07/10 & 06/30
Doc: substr()
You need to use substr function:
foreach ($billings as $billing) {
$resultstr[] = substr($billing->bl_date, 0, 5);
}

parse_str array return only last value

I am using ajax to submit the form and ajax value post as:
newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14
In PHP I am using parse_str to convert string to array,but it return only last value:
$newcoach = "newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
Result array having only last value:
Array
(
[newcoach] => 14
)
Any help will be appreciated...
Since you set your argument newcoach multiple times, parse_str will only return the last one. If you want parse_str to parse your variable as an array you need to supply it in this format with a '[ ]' suffix:
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
Example:
<?php
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]h=12&newcoach[]=13&newcoach[]=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
?>
Outputs:
Array ( [newcoach] => Array ( [0] => 6 [1] => 11 [2] => 12 [3] => 13 [4] => 14 ) )
Currently it is assigning the last value as all parameter have same name.
You can use [] after variable name , it will create newcoach array with all values within it.
$test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
echo '<pre>';
parse_str($test,$result);
print_r($result);
O/p:
Array
(
[newcoach] => Array
(
[0] => 6
[1] => 11
[2] => 12
[3] => 13
[4] => 14
)
)
Use this function
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$parsed_array = proper_parse_str($newcoach);

Remove string start from certain character? [duplicate]

This question already has answers here:
PHP substring extraction. Get the string before the first '/' or the whole string
(14 answers)
Closed 5 years ago.
For example I have an array
$array[] = ['name - ic'];
The result I want is
$new_Array[]=['name'];
How do I remove the string that start from the - since the name and ic will be different for everyone? Anyone can help?
Using explode method you can split string into array.
PHP
<?php
$array[] = ['name - ic'];
$array[] = ['name - bc - de'];
$new_Array = array();
foreach($array as $key=>$values){
foreach($values as $k=>$val){
$str = explode("-",$val);
$new_Array[$key][$k] = trim($str[0]);
}
}
?>
OUTPUT
Array
(
[0] => Array
(
[0] => name
)
[1] => Array
(
[0] => name
)
)
You can use explode function for the same.
$array = array('name - ic','abc - xyz','pqr-stu');
$newArray = array();
foreach($array as $obj):
$temp = explode('-',$obj);
$newArray[] = trim($temp[0]);
endforeach;
print_r($newArray);
Result
Array ( [0] => name [1] => abc [2] => pqr )
Let me know if it not works.

PHP reading data input from a text file

I have a text file which I must read, and use the data from.
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
How can I create an array of these strings in the following form?
array(
"name" => "number"
...
)
I tried this:
$handle = fopen("file.txt", "r");
fscanf($handle, "%d %d", $name, $number);
What then? No matter what I try, it only works for the first line.
sam 99912222
Added codes to have both types of output - ignoring and including the lines that don't have name-value pairs. Check them out below
This code goes through each line and gets only the ones that have both name and value (something[space]something)):
//$lines = ... each line of the file in an array
$vals = array();
foreach($lines as $v){
$tmp = explode(' ', $v);
if(count($tmp) > 1){
$vals[trim($tmp[0])] = trim($tmp[1]); // trim to prevent garbage
}
}
print_r($vals);
It will output this:
Array
(
[sam] => 99912222
[tom] => 11122222
[harry] => 12299933
)
See the code in action here.
If you need the values even if they didn't come in pairs, do it like this:
//$lines = ... each line of the file
$vals = array();
foreach($lines as $v){
$tmp = explode(' ', $v);
$name = '';
$number = '';
$tmp[0] = trim($tmp[0]);
if(count($tmp) > 1){
$name = $tmp[0];
$number = trim($tmp[1]);
}else{
if(is_numeric($tmp[0])){
$number = $tmp[0];
}else{
$name = $tmp[0];
}
}
$vals[] = array(
'name' => $name,
'number' => $number
);
}
print_r($vals);
And the output:
Array
(
[0] => Array
(
[name] =>
[number] => 3
)
[1] => Array
(
[name] => sam
[number] => 99912222
)
[2] => Array
(
[name] => tom
[number] => 11122222
)
[3] => Array
(
[name] => harry
[number] => 12299933
)
[4] => Array
(
[name] => sam
[number] =>
)
[5] => Array
(
[name] => edward
[number] =>
)
[6] => Array
(
[name] => harry
[number] =>
)
See the code in action here.
Data in file are inconsistent, best of is to use regex to identify what data you've got from each line.
$lines = file('file.txt'); // this will open file and split them into lines
$items = array();
foreach($lines as $line){
$name = null;
$number = null;
$nameFound = preg_match("|([A-Za-z]+)|", $line, $matches);
if($nameFound){
$name = $matches[0];
}
$numberFound = preg_match("|([0-9]+)|", $line, $matches);
if($numberFound){
$number = $matches[0];
}
$items[] = array('name' => $name, 'number' => $number);
}
Then in items you should find parsed data from file.
To make it just extract full format data just change lines with regex into one line like this:
$lines = file('file.txt'); // this will open file and split them into lines
$items = array();
foreach($lines as $line){
$userFound = preg_match("/([A-Za-z]+) ([0-9]+)/", $line, $matches);
if($userFound){
$items[$matches[1]] = $matches[2];
}
}
With the Algorithm below, you can simply parse each individual line of the Text-File Contents into an array with the 1st Word or Digit(s) on each line as the Key and the 2nd Word as the Value. When the 2nd word or group of words do not exist, a NULL is assigned to that Key. For re-usability, this algorithm has been encapsulated into a Function. Here you go:
<?php
function parseTxtFile($txtFile){
$arrTxtContent = [];
if(!file_exists($txtFile)){ return null;}
$strFWriteTxtData = file_get_contents($txtFile);
if(empty($strFWriteTxtData)){return null;}
$arrFWriteInfo = explode("\n", $strFWriteTxtData);
foreach($arrFWriteInfo as $iKey=>$lineData){
$arrWriteData = explode(", ", $lineData);
foreach($arrWriteData as $intKey=>$strKeyInfo){
preg_match("#(^[a-z0-9_A-Z]*)(\s)(.*$)#i", $strKeyInfo, $matches);
preg_match("#(^[a-z0-9_A-Z]*)(\s*)?$#i", $strKeyInfo, $matches2);
if($matches) {
list(, $key, $null, $val) = $matches;
if (!array_key_exists($key, $arrTxtContent)) {
$arrTxtContent[$key] = $val;
}else{
$iKey = $intKey + 1;
$key = $key . "_{$iKey}";
$arrTxtContent[$key] = $val;
}
}else if($matches2) {
list(, $key, $null) = $matches2;
if (!array_key_exists($key, $arrTxtContent)) {
$arrTxtContent[$key] = null;
}else{
$key = preg_match("#_\d+#", $key, $match)? $key . $match[0] : "{$key}_1";
$arrTxtContent[$key] = null;
}
}
}
}
return $arrTxtContent;
}
var_dump(parseTxtFile(__DIR__ . "/data.txt"));
Just call the function parseTxtFile($txtFile) passing it the path to your text File and it will return an Array that looks something like below:
array (size=7)
3 => null
'sam' => string '99912222' (length=8)
'tom' => string '11122222' (length=8)
'harry' => string '12299933' (length=8)
'sam_1' => null
'edward' => null
'harry_1' => null
Hope this could help a bit....
Cheers & Good-Luck ;-)

Categories