php string variable containing as input for array function - php

Why this does not work?
$stringhaha =" 1 => General,
2 => Business,
3 => Entertainment,
4 => Health,
5 => Politics,
6 => Sci/Tech,
7 => Sports,
8 => News";
$all_categories = array($stringhaha);
print_r($all_categories);
(will give an array with 1 item.)
While this works:
If I include the variable content like this it will create properly an array with 8 items:
$all_categories = array(1 => General,
2 => Business,
3 => Entertainment,
4 => Health,
5 => Politics,
6 => Sci/Tech,
7 => Sports,
8 => News);
print_r($all_categories);

What is happening is exactly what you should expect: you've declared an array that contains one string.
It doesn't matter that your string looks like an array to us humans, PHP is merely PHP, and can't magically detect that you want it to parse an array from a string.
giorgio79, meet PHP Docs, your new best friend.

It's called language syntax. You cannot do whatever you want. You have to speak the language how it was designed.
This doesn't work either
message = hello
Why? Because it's not syntactically correct. Same applies for your example with array.
This is correct
$message = 'hello';
Every language has rules and you have to respect them. Good luck.

I think the correct syntax is:
$all_categories = array(1 => "General",
2 => "Business",
3 => "Entertainment",
4 => "Health",
5 => "Politics",
6 => "Sci/Tech",
7 => "Sports",
8 => "News");
print_r($all_categories);
You do want an array of strings, right?

Related

Find and Replace Multi-Row Phrases/text Within PHP Arrays without damaging the array

Lets say I have an array:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Sundays',
[4] => 'which are also pretty good days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);
Keeping the structure of this array intact, I want to be able to replace phrases within it, even if they spill over to the next or previous string. Also I don't want punctuation or case to impact it.
Examples:
String to Find:
"Sundays which are also pretty good"
Replace with:
"Mondays which are also pretty great"
After replace:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Mondays',
[4] => 'which are also pretty great days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);
Curious if there is an ideal way of doing this. My original thought was, I would turn the array into a string, strip out punctuation and spaces, count the characters and replace the phrase based on the character count. But, it is getting rather complex, but it is a complex problem
This is a job for regular expressions.
The method I used was to implode the array with some glue (i.e. '&'). Then I generated a regular expression by inserting a zero-or-one check for '&' in between each character in the find string.
I used the regular expression to replace occurrences of the string we were looking for with the replacement string. Then I exploded the string back into an array using the same delimiter as above ('&')
$myarray = [
0 => 'Johnny likes to go to school',
1 => 'but he only likes to go on Saturday',
2 => 'because Saturdays are the best days',
3 => 'unless you of course include Mondays',
4 => 'which are also pretty great days too.',
5 => 'Sometimes Johnny likes picking Strawberrys',
6 => 'with his mother in the fields',
7 => 'but sometimes he likes picking blueberries'
];
// preg_quote this because we're looking for the string, not for a pattern it might contain
$findstring = preg_quote("Sundays which are also pretty good");
// htmlentities this in case it contains a string of characters which happen to be an html entity
$replacestring = htmlentities("Mondays which are also pretty great");
// Combine array into one string
// We use htmlentitles to escape the ampersand, so we can use it as a sentence delimeter
$mystring = implode("&", array_map('htmlentities', $myarray));
// Turns $findString into:
// S\&?u\&?n\&?d\&?a\&?y\&?s\&? \&?w\&?h\&?i\&?c\&?h\&? \&?a\&?r\&?e\&?
// \&?a\&?l\&?s\&?o\&? \&?p\&?r\&?e\&?t\&?t\&?y\&? \&?g\&?o\&?o\&?d
$regexstring = implode("\&?", str_split($findstring));
// Johnny likes to go to school&but he only likes to go on Saturday&because Saturdays are the
// best days&unless you of course include Mondays&which are also pretty great days
// too.&Sometimes Johnny likes picking Strawberrys&with his mother in the fields&but sometimes
// he likes picking blueberries
$finalstring = preg_replace("/$regexstring/", $replacestring, $mystring);
// Break string back up into array, and return any html entities which might have existed
// at the beginning.
$replacedarray = array_map('html_entity_decode', explode("&", $finalstring));
var_dump($replacedarray);

Is this normal behaviour in php arrays? Array size get shortened when using numbered indexes out of order

So I'm learning Php, so as I was messing around with arrays to see how they work, I stumbled into this when I made two arrays.
$TestArray1 = array( 1 => 1, "string" => "string", 24, "other", 2 => 6, 8);
$TestArray2 = array( 6 => 1, "string" => "string", 24, "other", 1 => 6, 8);
But when I print them out with print_r() this is what I get (this also happens with var_dump by the way)
Array ( [1] => 1 [string] => string [2] => 6 [3] => other [4] => 8 )
Array ( [6] => 1 [string] => string [7] => 24 [8] => other [1] => 6 [9] => 8 )
As far as I can tell, by putting the two in the second array it overwrites the next possible spot with no key and then keeps going, shortening the array. So I thought that meant that if I use a 1 it would put it at the start but that does not happen either.
Is this normal or is there something wrong with my php installation?
Im using Ampps in windows 10 with php 7.3.
Thanks in advance
Good question.
What's happening is that when determining automatic numeric indexes, PHP will look to the largest numeric index added and increment it (or use 0 if there are none).
The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.
What's happening with your first array is that as it is evaluated left-to-right, 24 is inserted at index 2 because the last numeric index was 1 => 1.
Then when it gets to 2 => 6, it overwrites the previous value at index 2. This is why 24 is missing from your first array.
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
Here's a breakdown
$TestArray1 = [1 => 6]; // Array( [1] => 6 )
// no index, so use last numeric + 1
$TestArray1[] = 24; // Array( [1] => 6, [2] => 24 )
$TestArray1[2] = 6; // Array( [1] => 6, [2] => 6 )
When you manually add numeric indexes that are lower than previous ones (ie $TestArray2), they will be added as provided but their position will be later.
This is because PHP arrays are really maps that just pretend to be indexed arrays sometimes, depending on what's in them.
References are from the PHP manual page for Arrays

Replace first character of sting in PHP with rules

I'm wanting to replace the first character of a string with a specific character depending on its value,
A = 0
B = 1
C = 2
Is there a way to do this based on rules? In total I will have 8 rules.
Ok, so I'm editing this to add more information as I don't think some people understand / want to help without the full picture...
My string will be any length between 5 and 10 characters
Capitals will not factor into this, it is not case sensitive
Currently there is no code, I'm not sure the best way to do this. I can write an if statement on a substring, but I know straight away that is inefficient.
Below is the before and after that I am expecting, I have kept these examples simple but all I am looking to do is replace the first character with a specific character depending on its value. For now, there are eight rules, but this could grow in the future
INPUT OUTPUT
ANDREW 1NDREW
BRIAN 2RIAN
BOBBY 2OBBY
CRAIG 3RAIG
DAVID 4AVID
DUNCAN 4UNCAN
EDDIE 5DDIE
FRANK 6RANK
GEOFF 7EOFF
GIANA 7IANA
HAYLEY 8AYLEY
So as you can see, pretty straight forward, but is there a simple way to specifically specify what a character should be replaced by?
Assuming all the rules are for single characters, like in the example, it would be easisest to code them in to a dictionary:
$rules = array('A' => 0, 'B' => 0 /* etc... */);
$str[0] = $rules[$str[0]];
I think this is what you want.
<?php
$input = array('ANDREW','BRIAN','BOBBY','CRAIG','DAVID','DUNCAN','EDDIE','FRANK','GEOFF','GIANA','HAYLEY');
$array = range('A','Z');
$array = array_flip(array_filter(array_merge(array(0), $array)));
$output = [];
foreach($input as $k=>$v){
$output[] = $array[$v[0]].substr($v, 1);
}
print_r($output);
?>
Output:
Array (
[0] => 1NDREW
[1] => 2RIAN
[2] => 2OBBY
[3] => 3RAIG
[4] => 4AVID
[5] => 4UNCAN
[6] => 5DDIE
[7] => 6RANK
[8] => 7EOFF
[9] => 7IANA
[10] => 8AYLEY
)
DEMO: https://3v4l.org/BHLPk

number of occurrences of every word on page

I am attempting to count the number of occurrences of every unique word on a page (think SEO 'word count' that you see on woorank etc. - but not for that purpose!)
I am really struggling on how to set this up:-
At the moment I am thinking of reading each word and then checking if it is unique against an array -> if unique add to array with occurences=>1 - then if I find the same word later just +1.
However this seems really cumbersome and slow for large blocks of text (especially as I will have to strip commas etc, convert all to lower case etc.) -> is there are a better way, has someone got a code snippet or library for this task?
For clarity
The Cat ran away with the hat. The spoon had already run away with another cat, far far away.
Would yield:
the => 3,
away => 3,
cat => 2,
with => 2,
far => 2,
spoon => 1,
hat => 1,
ran => 1,
run => 1,
had => 1,
another => 1,
already => 1
Thanks in advance - if there is no better way then that is fine!
ASIDE
I contemplated do a replace($word,"") on all words once found and counted -> but this seems just as cumbersome.
Use array_count_values() in conjunction with str_word_count():
$wordCounts = array_count_values(str_word_count(strtolower($sentence), 1));
arsort($wordCounts);
Output:
Array
(
[the] => 3
[away] => 3
[cat] => 2
[far] => 2
[with] => 2
[run] => 1
[another] => 1
[already] => 1
[hat] => 1
[ran] => 1
[spoon] => 1
[had] => 1
)
Demo
have a look at this article: http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
Split all the words (you could use a tokenizer like the ones users in Solr to "clean" them), put then in array, sort it, and array unique count. It really would depend on the language, but it will always be faster to use the language native functions that iterate the text by yourself.
In php:
$array = preg_split('/[\s,\.]+/', strtolower($text));
$unique = array_count_values($array);
print_r($unique);

Get the real difference between two arrays in php

I'm trying to get the difference between two arrays, but with array_diff, array_diff_assoc, or array_diff_key I can't get what I want..
Array 1 :
0 => 424012,
1 => 423000,
2 => 425010,
3 => 431447,
4 => 421001,
5 => 421002,
Array 2 :
0 => 424012,
1 => 423000,
2 => 425010,
3 => 431447,
4 => 431447,
5 => 421001,
6 => 421002,
array_diff = array ()
// empty
jarray_diff_assoc = array (
4 => 431447,
5 => 421001,
6 => 421002,
)
// OK but too much :)
array_diff_key = array(
6 => 421002
)
// nope i don't want that :(
I want 431447, cause it's only one time in the first array and twice in the second.
Regards, Tony
Is that exactly what you want? Only those that occur one time in the first, and two times in the second?
You can basically write your own function for that. Search through the second array, get a list of values that occur two times (or more than once, depending on what it is that you actually want), and then search for those in the first one (this you can do using a built-in PHP function array_intersect).

Categories