Iterating through Array of Arrays generating unwanted output - php

I am having issues when iterating through an array of arrays in PHP.
I have the following array, which I have posted to the page using Ajax.
Array (
[0] => Array ( [0] => T64 [1] => Array ( [name] => T64 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[1] => Array ( [0] => T65 [1] => Array ( [name] => T65 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[2] => Array ( [0] => T91 [1] => Array ( [name] => T91 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) ) )
I have tried to print all of the inner values using the below method, however it always prints a T (on its own line), before each desired value.
foreach($sOptions as $row => $innerArray){
foreach($innerArray as $innerRow => $value){
print $value['dummyA'] . "<br/>";
print $value['dummyB'] . "<br/>";
print $value['dummyC'] . "<br/>";
}
}
Output:
T
T
T
2
2
2
T
T
T
2
2
2
T
T
T
2
2
2
Would anyone be able to give be some incite to where these T values are coming from?

It is obvious. You are trying to get indexed value of the actual value from second level array using a string index that does not exists.
Because any string can be accessed as an array then the non existing string index is interpreted as false so it returns first value, ie zero-index character from the string accessed as an array.
In first case the value T64 is actually accessed as array('T','6','1') so it returned T.
<?php
// simple example
// Get the first character of a string
$str = 'T64';
echo "First character is: ". $str[0] .PHP_EOL;
echo "Second character is: ". $str[1] .PHP_EOL;
echo "Third character is: ". $str[2] .PHP_EOL;
echo PHP_EOL;
echo "Applied to your code:". PHP_EOL;
$sOptions = Array ( Array ( 'T64' ) );
print_r($sOptions[0][0]['invalid string index']);
Look at the demo: https://eval.in/1063420
Output:
First character is: T
Second character is: 6
Third character is: 4
T
Note: turn on error reporting to simplify your debugging ;) How do I get PHP errors to display?
More reading about accessing strings as array in described in PHP manual Strings esspecialy Example #11 and later.

can you try to use only one foreach ? I haven't try this solution but you can try to do something of similar
foreach($sOptions as $row => $innerArray){
$value = $innerArray[1]
print $value['dummyA'] . "<br/>";
print $value['dummyB'] . "<br/>";
print $value['dummyC'] . "<br/>";
}

You can also use array_column to isolate the part you want to iterate.
foreach(array_column($arr,1) as $row => $value){
echo $value['dummyA'] . "\n";
echo $value['dummyB'] . "\n";
echo $value['dummyC'] . "\n";
}
This means the code will only iterate the following:
array(3) {
[0]=>
array(4) {
["name"]=>
string(4) "T64 "
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(2) "2 "
}
[1]=>
array(4) {
["name"]=>
string(3) "T65"
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(1) "2"
}
[2]=>
array(4) {
["name"]=>
string(4) "T91 "
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(2) "2 "
}
}
https://3v4l.org/YA6Vq

Related

Phone Number Regex Conditions

I need to create a regex function to check phone numbers entered on a phone number field based on these conditions.
• if the number starts with either 6, 8 or 9 and another 7 digits
• or if the number starts with either +656, +658 or +659 and another 7 digits
So basically its singapore phone number with +65 being the country code
6, 8 or 9 are the only starting digit of phone numbers.
I have tried code below but it wont work.
add_filter( 'gform_phone_formats', 'sg_phone_format' );
function sg_phone_format( $phone_formats ) {
$phone_formats['sg'] = array(
'label' => 'Singapore',
'mask' => false,
'regex' => '/^[689]\d{7}$/D|/^(\+656)\d{7}$/D|/^(\+658)\d{7}$/D|/^(\+659)\d{7}$/D',
);
return $phone_formats;
}
Thank you!
I would use this regex pattern for Singapore numbers:
^(?:\+65)?[689][0-9]{7}$
Sample script:
$number = "+6587654321";
if (preg_match("/^(?:\+65)?[689][0-9]{7}$/", $number)) {
echo "MATCH";
}
So basically the set condition for a regex match can be found by alternating a grouping of sets that match the occurrences of the desired character or number, like so:
<code>
//$regex = '/\+65+[?:6?8:?:9]+[0-9]{3}+[0-9]{4}/'; //wrong
// Edited the following lines
$regex = '/(?:\+65[6|8|9]+[\d]{7})|(?:\+65[689][\-|\s|\/][0-9]{3}+[\-|\s|\/][0-9]{4})/';
$phone = '+6561234567,+6587654321,+659-432-1567,+6594321567,+659 765 4321,+658/765/1234,+659--432--1567,+6555?:?1231234'; //test string
//Match $var against a regular expression
preg_match_all($regex, $phone, $matches, PREG_SET_ORDER, 0);
//var_dump
var_dump($matches) . " \n";
//print_r
print_r ($matches) . " \n";
//echo single value array();
echo $matches[0][0];
echo "<br />";
echo $matches[1][0];
echo "<br />";
echo $matches[2][0];
echo "<br />";
echo $matches[3][0];
echo "<br />";
echo $matches[4][0];
echo "<br />";
echo $matches[5][0];
echo "<br />";
echo $matches[6][0];
</code>
The result from the above code is as follow:
<pre>
//var_dump
array(6) { [0]=> array(1) { [0]=> string(11) "+6561234567" } [1]=> array(1) { [0]=> string(11) "+6587654321" } [2]=> array(1) { [0]=> string(13) "+659-432-1567" } [3]=> array(1) { [0]=> string(11) "+6594321567" } [4]=> array(1) { [0]=> string(13) "+659 765 4321" } [5]=> array(1) { [0]=> string(13) "+658/765/1234" } }
//print_r
Array ( [0] => Array ( [0] => +6561234567 ) [1] => Array ( [0] => +6587654321 ) [2] => Array ( [0] => +659-432-1567 ) [3] => Array ( [0] => +6594321567 ) [4] => Array ( [0] => +659 765 4321 ) [5] => Array ( [0] => +658/765/1234 ) )
//echo single value array();
+6561234567
+6587654321
+659-432-1567
+6594321567
+659 765 4321
+658/765/1234
</pre>
You can easily match more personalized regular expressions by setting specific conditions to match the string by escaping additional characters with
\ or any whitespace character with
\s
<code>
// add more characters to regex to match +659-432-1567
$regex = '/\+65[6|8|9]+[\-][0-9]{3}+[\-][0-9]{4}/';
</code>
The result from the modified regular expression will be
<pre>
array(1) { [0]=> array(1) { [0]=> string(13) "+659-432-1567" } }
Array ( [0] => Array ( [0] => +659-432-1567 ) )
+659-432-1567 //echo one match out of six
</pre>

PHP Why two same value from two different string are not equal to each other

Why are these two strings not equal?
I tried to get the same name so I can create a file, however I cannot get two strings equal to each other, even though I think both strings have the same value.
I uploaded var_dump output
any idea how to fix it?
$selectCategory = scandir($_SERVER['DOCUMENT_ROOT'].'/database/');
$cat = explode('.',$category);
print_r($cat);
print_r($selectCategory);
if($cat[0] == $selectCategory[2]){
echo " true";
}
else{
echo "no";
}
output:
Array ( [0] => bus [1] => php )
Array ( [0] => . [1] => .. [2] => bus [3] => fruit )
no
This is var_dump output
array(2) { [0]=> string(5) " bus" [1]=> string(3) "php" }
array(4) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(3) "bus" [3]=> string(5) "fruit" }
no
As you can see from the var_dump output the items you are comparing are different lengths. There is a space and possibly a hidden character in the $cat one:
To trim all space and some other characters use this:
$cat = array_map('trim', $cat);
$selectCategory = array_map('trim', $selectCategory);

Search item in an array using PHP

I want to search an item like "January" or "February" in an array that looks like this
Array
(
[0] => January
[1] => February
[2] => March
[3] => April
)
This what I have tried so far. But not working.
if ( in_array("January", $date_array) ) {
echo "Found item in Array";
} else {
echo "Didn't find item in Array";
}
result:
Didn't find item in Array
This is the result of var_dump()
array(4) {
[0]=>
string(9) "January
"
[1]=>
string(10) "February
"
[2]=>
string(7) "March
"
[3]=>
string(7) "April
"
}
Don't know, where line breaks are coming from, but you can remove them, for example, with array_map:
$date_array = array_map('trim', $date_array);
// and then use `in_array`

Simple array_diff not working

I have 2 arrays.
The first one is $teach_array and the second one is $langs_array.
Their respective values are:
$teach_array : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
$langs_array : Array ( [0] => 2 [1] => 3 )
Im trying to return a new array containing all the entries from $teach_array that are not present in $langs_array.
So the end result should be: Array ( [0] => 1 [3] => 4 [4] => 5 )
I have tried using a couple of methods including :
Option 1
$result = array_diff($teachArray, $language_1d_array);
This still returns all the values of $teach_array.
Option 2
$result = array_diff_key($teachArray, $language_1d_array);
However, this only returns Array ( [2] => 3 [3] => 4 [4] => 5 ) which is not correct.
Option 3
$result = array_values(array_diff_key($teachArray, $language_1d_array));
This returns the same result as Option 2. I also tried using only array_diff instead of array_diff_key and it returns the same result as Option 1.
I did a var_dump on both of my arrays and here is the result.
$teach_array : array(5) { [0]=> string(5) " 1 " [1]=> string(5) " 2 " [2]=> string(5) " 3 " [3]=> string(5) " 4 " [4]=> string(5) " 5 " }
$lang_array : array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }
hope you have already found the solution, but just in case I want to point you on following.
Blockquote
I did a var_dump on both of my arrays and here is the result.
$teach_array : array(5) { [0]=> string(5) " 1 " [1]=> string(5) " 2 " [2]=> string(5) " 3 " [3]=> string(5) " 4 " [4]=> string(5) " 5 " }
$lang_array : array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }
No single value from $teach_array matches any value of $lang_array.
Because there are differently formatted values, one array contains whitespaces before and after the value you want to match " 2 ".
var_dump($teach_array) => array(5) { [0]=> string(5) " 4 " ... }
var_dump($lang_array) => array(5) { [0]=> string(1) "2" ... }
I guess you have some whitespaces included. Please try again with:
$diff = array_diff(array_map('trim', $teach_array), $lang_array);
PHPTester just tested yours, works fine for me..?
$teachArray =[1,2,3,4,5];
$langsarray =[2,3];
$result = array_diff($teachArray,$langsarray);
print_r($result);
works and prints 1, 4, 5 for me.
BUT...here's a solution for what you're trying to acquire: the values in teacher array that are not in langs
$new_array = array();
foreach($teach_array as $item){ // Loop the teacher_array
if(!in_array($item,$langs_array)){ // If the teach_array value doesn't exist in the lang_array, add the value
$new_array[] = $item;
}
}
I'm sure theres a more elegant way, but this works:
$teach = [1, 2, 3,4, 5];
$langs = [2, 3];
$result = [];
foreach ($teach as $key => $t) {
if (!in_array($t, $langs)) {
$result[$key] = $t;
}
}
var_dump($result);
This is (basically) what you say you have. It works for me:
<?php
$fred = array(0=>1, 1=>2, 2=>3, 3=>4, 4=>5);
$bert = array(0=>2, 1=>3);
$res = array_diff($fred, $bert);
print_r($res);

PHP - Splitting string lines up into two variables

Not sure how I would do this but if someone could point me in the right track that'll be great, basically I've got a lone line of text in a variable which looks like this:
Lambo 1; Trabant 2; Car 3;
Then I want to split "Lambo" to it's own variable then "1" to it's own variable, and repeat for the others. How would I go and do this?
I know about explode() but not sure how I would do it to split the variable up twice etc.
As requested in the comments my desired output would be like this:
$Item = "Lambo"
$Quantity = 1
Then echo them out and go back to top of loop for example and do the same for the Trabant and Car
<?php
$in = "Lambo 1; Trabant 2; Car 3;";
foreach (explode(";", $in) as $element) {
$element = trim($element);
if (strpos($element, " ") !== false ) {
list($car, $number) = explode(" ", $element);
echo "car: $car, number: $number";
}
}
You can use explode to split the input on each ;, loop over the results and then split over each .
You can use preg_split and iterate over the array by moving twice.
$output = preg_split("/ (;|vs) /", $input);
You could use preg_match_all for getting those parts:
$line = "Lambo 1; Trabant 2; Car 3;";
preg_match_all("/[^ ;]+/", $line, $matches);
$matches = $matches[0];
With that sample data, the $matches array will look like this:
Array ( "Lambo", "1", "Trabant", "2", "Car", "3" )
$new_data="Lambo 1;Trabant 2;Car 3;" ;
$new_array=explode(";", $new_data);
foreach ($new_array as $key ) {
# code...
$final_data=explode(" ", $key);
if(isset($final_data[0])){ echo "<pre>".$final_data[0]."</pre>";}
if(isset($final_data[1])){echo "<pre>".$final_data[1]."</pre>";}
}
This places each word and number in a new key of the array if you need to acess them seperatly.
preg_match_all("/(\w+) (\d+);/", $input_lines, $output_array);
Click preg_match_all
http://www.phpliveregex.com/p/fM8
Use a global regular expression match:
<?php
$subject = 'Lambo 1; Trabant 2; Car 3;';
$pattern = '/((\w+)\s+(\d+);\s?)+/Uu';
preg_match_all($pattern, $subject, $tokens);
var_dump($tokens);
The output you get is:
array(4) {
[0] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[1] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[2] =>
array(3) {
[0] =>
string(5) "Lambo"
[1] =>
string(7) "Trabant"
[2] =>
string(3) "Car"
}
[3] =>
array(3) {
[0] =>
string(1) "1"
[1] =>
string(1) "2"
[2] =>
string(1) "3"
}
}
In there the elements 2 and 3 hold exactly the tokens you are looking for.

Categories